单词边界

2024-06-24 21:10:25 281
正则表达式单词边界匹配一个单词的开始或结束位置。

语法

\b

示例

\bword\b

匹配整个单词 word,而不是 sword 或 words。

解释:

  • \bword\b 在字符串 this is a word 中匹配 word,因为 word 两侧都是边界。
  • \bword\b 在字符串 this is a sword 中不匹配 word,因为 word 的左边不是边界。

代码示例

python

import re

pattern = r'\bword\b'
test_string = 'this is a word in a sentence'
matches = re.findall(pattern, test_string)
print(matches)  # ['word']