madfriend
madfriend

Reputation: 2430

regular expression matching a string that is followed with another string without capturing the latter

Is there an ability to make a lookahead assertion non-capturing? Things like bar(?:!foo) and bar(?!:foo) do not work (Python).

Upvotes: 5

Views: 3203

Answers (2)

David
David

Reputation: 6561

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

Upvotes: 1

zx81
zx81

Reputation: 41848

If you do bar(?=ber) on "barber", "bar" is matched, but "ber" is not captured.

Upvotes: 3

Related Questions