问题
I need to see if a line contains 2 numbers, and if the first one is less than 0.5:
if re.search('((?:\d|[.\-\+]\d|[\+\-]\.\d)[\d\.\-\+e]*)[^\d\.\-\+]+((?:\d|[.\-\+]\d|[\-\+]\.\d)[\d\.\-\+e]*)',foil[ifrom],re.IGNORECASE) and float(re.group(1))<0.5:
#above is wrong: no such thing as re.group(1)...
elif re.search('((?:\d|[.\-\+]\d|[\+\-]\.\d)[\d\.\-\+e]*)[^\d\.\-\+]+((?:\d|[.\-\+]\d|[\-\+]\.\d)[\d\.\-\+e]*)',foil[midsep+1],re.IGNORECASE) and float(re.group(1))>0.5:
#also wrong
What would be the correct way to do this? Is it even possible to access the results of the search inside the same "if" statement ?
回答1:
Use a walrus operator in Python 3.8+:
if (m := re.search(r'..REGEX HERE...', foil[ifrom], re.I)) and float(m.group(1))<0.5:
print(m.group(0)) # prints match value
elif:
...
else:
...
The match data object is assigned to m and m.group(1) access the Group 1 value that is available in the same if condition.
A quick test in Python console:
>>> import re
>>> s = "20"
>>> if (m := re.search(r'[0-9]+', s)) and int(m.group(0))>5:
... print(m.group(0))
... else:
... print("No")
...
20
>>>
来源:https://stackoverflow.com/questions/64796060/python-how-to-use-re-search-in-a-compound-if-statement-is-it-even-possible