\b
\bword\b
匹配整个单词 word,而不是 sword 或 words。
解释:
\bword\b
在字符串 this is a word
中匹配 word
,因为 word
两侧都是边界。\bword\b
在字符串 this is a sword
中不匹配 word
,因为 word
的左边不是边界。import re
pattern = r'\bword\b'
test_string = 'this is a word in a sentence'
matches = re.findall(pattern, test_string)
print(matches) # ['word']