\python的re和精确单词匹配中的b

2024-04-16 06:39:05 发布

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

如何使\b正确地尊重单词边界?例如,理解'and not's partial match。。。在

>>> import re
>>> str = "This is a test's test"
>>> p1 = r'\b' + 'test' + r'\b'
>>> re.findall(p1,str)
['test', 'test']

Tags: andtestimportreismatchnotthis
1条回答
网友
1楼 · 发布于 2024-04-16 06:39:05

使用negative look-ahead assertion,您可以确保匹配test,后面不跟{}。在

>>> import re
>>> s = "This is a test's test"
>>> re.findall(r"\btest\b(?!')", s)  # match `test` as long as it is not followed by "'"
['test']

顺便说一句,不要使用str作为变量名。它隐藏了内置函数/类型str。在

相关问题 更多 >