断言是指对匹配到的文本位置有要求,对应于上面正则匹配规则表中的边界匹配器和环视。
假如我们想要把下面文本中的 tom 替换成 jerry。注意一下,在文本中出现了 tomorrow 这个单词,
tomorrow 也是以 tom 开头的。
tom asked me if I would go fishing with him tomorrow.
这个时候就要求只匹配单词tom而不匹配包含tom的单词,实现这个效果最佳的办法就是使用单词边
界,可以看看效果:
于是我们的正则就可以编写为:
test_str = "tom asked me if I would go fishing with him tomorrow.atom and atomic."
re.sub('\btom\b', 'jerry', test_str)
结果:
'tom asked me if I would go fishing with him tomorrow.atom and atomic.'