Python:如何在复合if语句中使用re.search()(这可能吗?)

2024-09-27 17:43:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要查看一行是否包含两个数字,如果第一个小于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

正确的方法是什么?甚至可以在同一个“if”语句中访问搜索结果吗


Tags: andnoresearchifisgroup数字
1条回答
网友
1楼 · 发布于 2024-09-27 17:43:31

在Python 3.8+中使用walrus operator

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:
    ...

匹配数据对象被分配给m,并且m.group(1)访问在相同if条件下可用的组1值

Python控制台中的快速测试:

>>> 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
>>> 

相关问题 更多 >

    热门问题