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

use*_*770 4 python regex string

如何使 \b 正确尊重单词边界?例如,理解 ' 并且不进行部分匹配...

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

fal*_*tru 6

使用否定前瞻断言,您可以确保匹配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']
Run Code Online (Sandbox Code Playgroud)

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