我正在尝试在 python 中使用正则表达式搜索特定单词。
lst2 = ['Azmat', 'AZ', 'azim', 'Zard', 'Zardari']
pattern = re.compile(r"\bAZ|Zard\b", re.I)
for item in lst2:
if re.search(pattern, item):
print item
此代码产生:
Azmat
AZ
azim
Zard
为什么不只匹配“AZ”和“Zard”?
最佳答案
这是因为您的正则表达式匹配:
\bAZ
或
Zard\b
使用非捕获组来限制 |
运算符的“影响”:
\b(?:AZ|Zard)\b
这样,它显示为:\b
,然后是 AZ
或 Zard
,最后是 \b
。
关于python 正则表达式只匹配特定的词,而不是子集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21588008/