5

是否有能力使前瞻断言不被捕获?喜欢bar(?:!foo)bar(?!:foo)不工作的事情(Python)。

4

2 回答 2

3

如果你bar(?=ber) 在“barber”上做,“bar”被匹配,但“ber”没有被捕获。

于 2012-03-29T10:15:12.843 回答
1

您没有回答 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!
bar
于 2012-05-23T17:59:31.973 回答