#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2010
    Posts
    1
    Rep Power
    0

    Negative Lookahead question


    Hey all. I've done much googling, read the section on regular-expressions.info , experimented with an online tool, and even played around with powertoy, but I am stuck on understanding Negative Lookahead.

    My goal is to discern: "Line that begins with an apostrophe, and does not have the word generator in it."

    Could someone explain why this pattern:

    '.*(?!generator)

    doesn't achieve that goal, and suggest something which would? The example text I'm working with is:

    'blah blah
    'here is a generator text line

    Your advice would be so helpful!

    Thanks a lot.
    Michael
  2. #2
  3. Did you steal it?
    Devshed Supreme Being (6500+ posts)

    Join Date
    Mar 2007
    Location
    Washington, USA
    Posts
    13,965
    Rep Power
    9397
    Regular expressions always try to match. What you want is to not match. That means you have to be very explicit as to what the engine does.

    ^.*(?!generator) starts at the beginning of the string/line, grabs up as many characters as it possibly can - that means it hits the end of the line - and checks that "generator" does not come afterwards. If it does the engine will backtrack a character and test again, where it will match and return success.

    You need to tell the engine to look for "generator" after every character in the line. So it repeats "find a character and fail if there's a 'generator' after it" all the way until the end of the line.

IMN logo majestic logo threadwatch logo seochat tools logo