Python正则表达式匹配world,但排除某些短语

2024-09-29 23:15:07 发布

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

我得到了以下场景:

1)car is on fire
2)found fire crews on scene

我想在关键字“船员”不在的时候匹配火力。换句话说,我想1)返回“火”,2)不返回任何东西。你知道吗

regex = re.compile(r'\bfire (?!crews)\b')

但由于失火后空间缺失,未能与“汽车着火”匹配。你知道吗

提前谢谢。你知道吗


Tags: reison场景关键字scenecarfire
2条回答

你的正则表达式是

\bfire\b(?!.*\bcrews\b)

DEMO

如果你想打印整行的话你的正则表达式应该是

.*\bfire\b(?!.*\bcrews\b).*

Python代码

>>> import re
>>> data = """car is on fire
... found fire crews on scene"""
>>> m = re.search(r'\bfire\b(?!.*\bcrews\b)', data, re.M)
>>> m.group()
'fire'
>>> m = re.search(r'.*\bfire\b(?!.*\bcrews\b).*', data, re.M)
>>> m.group()
'car is on fire'

这里不需要正则表达式。您只需使用in关键字进行检查:

if "fire" in line and "crews" not in line:
    print("fire")

相关问题 更多 >

    热门问题