\b 称为单词边界(word boundary)符.
例如只想匹配 My cat is bad.中的cat 可以使用 \bcat\b
import re
harsh_str = [
'hello',
'Cat',
' cat',
'cat h',
'CAT',
'CAt-h',
'Cat_h']
#re.I要在compile的时候指定,注意\b在python中是回退符,正则模式之前一定要加r(raw string)
p = re.compile(
r
'\bcat\b', re.I)
p1 = re.compile(
r
'\bcat h\b', re.I)
p2 = re.compile(
r
'\bcat-h\b', re.I)
print([ s
for s in harsh_str
if re.search(p, s)])
print([ s
for s in harsh_str
if re.search(p1, s)])
print([ s
for s in harsh_str
if re.search(p2, s)])
输出:
['Cat', ' cat', 'cat h', 'CAT', 'CAt-h']
['cat h']
['CAt-h']
但是pattern p依然匹配到了 CAt-h.这是因为下划线_是单词字符,\b本身只占一位,有三种情况会匹配到,一种就是\b会匹配到两个字符之间,一个是单词字符,另一个不是单词字符。对于Cat_h t是单词字符,但是‘_’也是单词字符,所以没有匹配。下面的两个例子意思是这里的单词并非一定是连续的字符串。