相关疑难解决方法(0)

以特殊字符开头或结尾的单词的单词边界会产生意想不到的结果

假设我想匹配短语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)

另外,如果我删除 …

python regex

7
推荐指数
1
解决办法
1067
查看次数

标签 统计

python ×1

regex ×1