我得到了以下场景:
1)car is on fire
2)found fire crews on scene我想匹配火灾时,关键字“船员”不存在。换句话说,我希望1)返回"fire",2)什么也不返回。
regex = re.compile(r'\bfire (?!crews)\b')但由于火灾后缺少空间,它未能与“汽车着火”相匹配。
提前谢谢。
发布于 2014-07-26 13:40:26
你的判断力是,
\bfire\b(?!.*\bcrews\b)演示
如果你想打印整条线,那么你的正则表达式就是,
.*\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'发布于 2014-07-26 13:43:28
你不需要这里的审判。您只需检查in关键字:
if "fire" in line and "crews" not in line:
print("fire")https://stackoverflow.com/questions/24971579
复制相似问题