非单词边界(Non-word Boundary)

2024-06-24 21:10:32 283
匹配位置不在单词边界上的地方

语法

\B

示例

\Bword\B

匹配在单词 word 中间的位置,而不是在单词边界。

解释:

  • \Bword\B 在字符串 this is swordworded 中匹配 word,因为 word 的两侧都不是边界。
  • \Bword\B 在字符串 this is a word 中不匹配 word,因为 word 的两侧都是边界。

代码示例

python

import re

pattern = r'\Bword\B'
test_string = 'this is swordworded'
matches = re.findall(pattern, test_string)
print(matches)  # ['word']