5

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

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
madfriend
  • 2,400
  • 1
  • 20
  • 26
  • 6
    Lookaheads *are* non-capturing. Are you perhaps looking for *negative* lookahead? That's just `(?!foo)`. [ref](http://www.regular-expressions.info/lookaround.html) – Alan Moore Mar 25 '12 at 22:58

2 Answers2

3

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

zx81
  • 41,100
  • 9
  • 89
  • 105
1

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
David
  • 6,462
  • 2
  • 25
  • 22