问题
Is there an ability to make a lookahead assertion non-capturing? Things like bar(?:!foo) and bar(?!:foo) do not work (Python).
回答1:
If you do bar(?=ber)
on "barber", "bar" is matched, but "ber" is not captured.
回答2:
You didn't respond to Alan's question, but I'll assume that he's correct and you're interested in a negative lookahead assertion. IOW - match 'bar' but NOT 'barfoo'. In that case, you can construct your regex as follows:
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
来源:https://stackoverflow.com/questions/9864493/regular-expression-matching-a-string-that-is-followed-with-another-string-withou