\B
\Bword\B
匹配在单词 word 中间的位置,而不是在单词边界。
解释:
\Bword\B
在字符串 this is swordworded
中匹配 word
,因为 word
的两侧都不是边界。\Bword\B
在字符串 this is a word
中不匹配 word
,因为 word
的两侧都是边界。import re
pattern = r'\Bword\B'
test_string = 'this is swordworded'
matches = re.findall(pattern, test_string)
print(matches) # ['word']