是否有能力使先行断言不被捕获?像bar(?:!foo)和bar(?!:foo)这样的东西不工作(Python)。
发布于 2012-03-29 18:15:13
如果在“bar(?=ber)”上使用"barber",则会匹配"bar“,但不会捕获"ber”。
发布于 2012-05-24 01:59:32
您没有回答Alan的问题,但我假设他是正确的,并且您对负面的先行断言感兴趣。IOW -匹配'bar‘而不是'barfoo’。在这种情况下,您可以按如下方式构造正则表达式:
myregex = re.compile('bar(?!foo)')
for example, from the python console:
>>> import re
>>> myregex = re.compile('bar(?!foo)')
>>> m = myregex.search('barfoo')
>>> print m.group(0) <=== Error here because match failed
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'group'
>>> m = myregex.search('bar')
>>> print m.group(0) <==== SUCCESS!
barhttps://stackoverflow.com/questions/9864493
复制相似问题