【发布时间】:2012-05-03 23:26:28
【问题描述】:
据我了解
(.)(?<!\1)
永远不应该匹配。实际上,php 的preg_replace 甚至拒绝编译它,ruby 的gsub 也是如此。不过,python re 模块似乎有不同的看法:
import re
test = 'xAAAAAyBBBBz'
print (re.sub(r'(.)(?<!\1)', r'(\g<0>)', test))
结果:
(x)AAAA(A)(y)BBB(B)(z)
谁能为这种行为提供合理的解释?
更新
此行为似乎是 a limitation 模块中的 re。替代的regex 模块似乎可以正确处理断言中的组:
import regex
test = 'xAAAAAyBBBBz'
print (regex.sub(r'(.)(?<!\1)', r'(\g<0>)', test))
## xAAAAAyBBBBz
print (regex.sub(r'(.)(.)(?<!\1)', r'(\g<0>)', test))
## (xA)AAA(Ay)BBB(Bz)
请注意,与pcre 不同,regex 还允许可变宽度的lookbehinds:
print (regex.sub(r'(.)(?<![A-Z]+)', r'(\g<0>)', test))
## (x)AAAAA(y)BBBB(z)
最终,regex 将被包含在标准库中,正如PEP 411 中所述。
【问题讨论】:
-
匹配就像你使用了
(.)(?!\1)。
标签: python regex python-3.x python-2.7