【发布时间】:2022-12-05 23:46:14
【问题描述】:
假设我想匹配短语 test Sortes\index[persons]{Sortes} text 中出现的短语 Sortes\index[persons]{Sortes}。
使用 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}'>
这可行,但我想避免使用搜索模式Sortes 对短语test Sortes\index[persons]{Sortes} text 给出肯定的结果。
>>> 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}'>
此外,documentation 说的是 \b
请注意,形式上,\b 被定义为 \w 和 \W 字符之间的边界(反之亦然),或者 \w 和字符串的开头/结尾之间的边界。
所以我尝试用
(\W|$)替换最后的\b:>>> 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,它是一个单词字符,因此存在单词边界。