假设我想匹配短语Sortes\index[persons]{Sortes}中短语的存在test Sortes\index[persons]{Sortes} text。
使用 pythonre我可以做到这一点:
>>> 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}'>
Run Code Online (Sandbox Code Playgroud)
这有效,但我想避免搜索模式Sortes对短语给出肯定的结果test Sortes\index[persons]{Sortes} text。
>>> re.search(re.escape('Sortes'), match)
<_sre.SRE_Match object; span=(5, 11), match='Sortes'>
Run Code Online (Sandbox Code Playgroud)
所以我使用\b模式,像这样:
search = r'\b' + re.escape('Sortes\index[persons]{Sortes}') + r'\b'
match = 'test Sortes\index[persons]{Sortes} text'
re.search(search, match)
Run Code Online (Sandbox Code Playgroud)
现在,我没有得到匹配。
如果搜索模式不包含任何字符[]{},则它有效。例如:
>>> re.search(r'\b' + re.escape('Sortes\index') + r'\b', 'test Sortes\index test')
<_sre.SRE_Match object; span=(5, 17), match='Sortes\\index'>
Run Code Online (Sandbox Code Playgroud)
另外,如果我删除 …