Re: python regex "negative lookahead assertions" problems

Discussion in 'Python' started by MRAB, Nov 22, 2009.

  1. MRAB

    MRAB Guest

    Tim Chase wrote:
    >>>>> import re
    >>>>> line='2009-11-22 12:15:441 lmqkjsfmlqshvquhsudfhqf qlsfh
    >>>>> qsduidfhqlsiufh qlsiuf qldsfhqlsifhqlius dfh warning qlsfj lqshf
    >>>>> lqsuhf lqksjfhqisudfh qiusdfhq iusfh'
    >>>>> re.match('.*(?!warning)',line)

    >> <_sre.SRE_Match object at 0xb75b1598>
    >>
    >> I would expect that this would NOT match as it's a negative lookahead
    >> and warning is in the string.

    >
    > This first finds everything (".*") and then asserts that "warning"
    > doesn't follow it, which is correct in your example. You may have to
    > assert that "warning" doesn't exist at every point along the way:
    >
    > re.match(r'(?:(?!warning).)*',line)
    >
    > which will match up-to-but-not-including the "warning" text. If you
    > don't want it at all, you'd have to also anchor the far end
    >
    > re.match(r'^(?:(?!warning).)*$',line)
    >
    > but in the 2nd case I'd just as soon invert the test:
    >
    > if 'warning' not in line:
    > do_stuff()
    >

    The trick is to think what positive lookahead you'd need if you wanted
    check whether 'warning' is present:

    '(?=.*warning)'

    and then negate it:

    '(?!.*warning)'

    giving you:

    re.match(r'(?!.*warning)', line)
    MRAB, Nov 22, 2009
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Xah Lee
    Replies:
    1
    Views:
    941
    Ilias Lazaridis
    Sep 22, 2006
  2. Xah Lee
    Replies:
    8
    Views:
    462
    Ilias Lazaridis
    Sep 26, 2006
  3. Replies:
    3
    Views:
    760
    Reedick, Andrew
    Jul 1, 2008
  4. Jelle Smet
    Replies:
    2
    Views:
    743
    Helmut Jarausch
    Nov 23, 2009
  5. Xah Lee
    Replies:
    2
    Views:
    218
    Xah Lee
    Sep 25, 2006
Loading...

Share This Page