[英]Python regex match world but exclude certain phrase
I got the following scenario: 我有以下场景:
1)car is on fire
2)found fire crews on scene
I want to match fire when keyword "crews" NOT present. 当关键字“工作人员”不存在时,我想匹配火。 The other word, I want to 1) return "fire", and 2) returns nothing.
换句话说,我想1)返回“火”,2)什么也不返回。
regex = re.compile(r'\bfire (?!crews)\b')
but it failed to match "car is on fire" due to missing space after fire. 但由于火灾后失去了空间,它未能与“汽车着火”相匹配。
Thanks in advance. 提前致谢。
Your regex would be, 你的正则表达式是,
\bfire\b(?!.*\bcrews\b)
If you want to print the whole line then your regex would be, 如果你想打印整行,你的正则表达式将是,
.*\bfire\b(?!.*\bcrews\b).*
Python code, 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'
You don't need regex here. 你这里不需要正则表达式。 You can just check with the
in
keyword: 您只需使用
in
关键字检查:
if "fire" in line and "crews" not in line:
print("fire")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.