假设我想要在这个短语中匹配短语 Sortes\index[persons]{Sortes}
的存在:test Sortes\index[persons]{Sortes} text
。
使用Python的re
模块,我可以这样做:
>>> search = re.escape('Sortes\index[persons]{Sortes}')
>>> match = 'test Sortes\index[persons]{Sortes} text'
>>> re.search(search, match)
<_sre.SRE_Match object; span=(5, 34), match='Sortes\\index[persons]{Sortes}'>
这个方法是可行的,但我希望避免在短语 test Sortes\index[persons]{Sortes} text
中搜索模式Sortes
后得到肯定的结果。
>>> re.search(re.escape('Sortes'), match)
<_sre.SRE_Match object; span=(5, 11), match='Sortes'>
我使用\b
模式,像这样:
search = r'\b' + re.escape('Sortes\index[persons]{Sortes}') + r'\b'
match = 'test Sortes\index[persons]{Sortes} text'
re.search(search, match)
现在,我找不到匹配项。
如果搜索模式不包含任何[]{}
中的字符,它就能够工作。例如:
>>> re.search(r'\b' + re.escape('Sortes\index') + r'\b', 'test Sortes\index test')
<_sre.SRE_Match object; span=(5, 17), match='Sortes\\index'>
此外,如果我删除最后的r'\b'
,它也可以正常工作:
re.search(r'\b' + re.escape('Sortes\index[persons]{Sortes}'), 'test Sortes\index[persons]{Sortes} test')
<_sre.SRE_Match object; span=(5, 34), match='Sortes\\index[persons]{Sortes}'>
此外,文档关于
\b
的说明如下:
因此,我尝试将最后一个请注意严格定义,\b 是一个\w字符和\W字符(或反之)之间的边界,或者是\w字符和字符串开头/结尾之间的边界。
\b
替换为(\W|$)
:>>> re.search(r'\b' + re.escape('Sortes\index[persons]{Sortes}') + '(\W|$)', 'test Sortes\index[persons]{Sortes} test')
<_sre.SRE_Match object; span=(5, 35), match='Sortes\\index[persons]{Sortes} '>
哎呀,它起作用了!这是怎么回事?我错过了什么吗?
s
,它是单词字符,因此存在单词边界。 - Sebastian Proske