据我了解,
(.)(?<!\1)
永远不应该匹配。其实php的preg_replace
甚至拒绝编译这个,ruby 也是如此gsub
。蟒蛇re
模块似乎有不同的意见:
import re
test = 'xAAAAAyBBBBz'
print (re.sub(r'(.)(?<!\1)', r'(\g<0>)', test))
Result:
(x)AAAA(A)(y)BBB(B)(z)
谁能为这种行为提供合理的解释?
Update
这种行为似乎是一个限制 in the 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.