I have a large file which contains many occurences of certain syntax: (width 0.15).
The number 0.15 can be any floating point number. I wish to find all instances of these numbers and modify them. I know how to modify them using float('0.15')+modifier and also I know how to make a string of the result again.
I have trouble finding the numbers. I looked at the re module but don’t quite know how to match the numbers themselves and not include the environment with the match.
So I know how to match all the occurrences of the entire environment (width 0.15) using re. I know how to modify the number string. But I don’t know how to match for the actual number within the environment. How to do this ?
>Solution :
IIUC, you could use lookarounds:
s = '(width 0.15)'
match = re.search('(?<=\(width )\d+(?:\.\d*)?(?=\))', s)
output:
match.group()
# '0.15'
For all occurrences + conversion to float:
out = list(map(float, re.findall('(?<=\(width )\d+(?:\.\d*)?(?=\))', )s))
output:
[0.15]
regex:
(?<=\(width ) # match should be preceded by "(width "
\d+ # one or more digits
(?:\.\d*)? # optionally, a dot with zero or more digits
(?=\)) # match should be followed by ")"