Python: How to use re.search() in a compound if statement (is it even possible?)

亡梦爱人 提交于 2021-01-28 07:53:07

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!