2024-09-29 23:15:07 发布
网友
我得到了以下场景:
1)car is on fire 2)found fire crews on scene
我想在关键字“船员”不在的时候匹配火力。换句话说,我想1)返回“火”,2)不返回任何东西。你知道吗
regex = re.compile(r'\bfire (?!crews)\b')
但由于失火后空间缺失,未能与“汽车着火”匹配。你知道吗
提前谢谢。你知道吗
你的正则表达式是
\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关键字进行检查:
in
if "fire" in line and "crews" not in line: print("fire")
你的正则表达式是
DEMO
如果你想打印整行的话你的正则表达式应该是
Python代码
这里不需要正则表达式。您只需使用
in
关键字进行检查:相关问题 更多 >
编程相关推荐