Reputation: 6222
given the content:
hello bob
hello my name is bob
I am trying to match hello bob
using a negative lookahead. The regex hello.*(?!my name is).*bob
matches both lines. The regex hello .*(?!my name is) .*bob
matches the second line.
How can I match just the first line, and why on earth does the negative lookahead match the line that it's supposed to NOT match against? What am I doing wrong?
Upvotes: 0
Views: 41
Reputation:
Using negative lookahead is overkill if you only need to match the first thing, so this regex should be enough:
^hello bob$
Using the start of line anchor (^
) and the end of line anchor ($
), only hello bob
will satisfy that regex.
Upvotes: 1
Reputation: 8389
The greedy .*
before the negative lookahead is what's keeping it from working correctly. This does the match you're looking for:
/hello (?!my name is).*bob/
Alternatively, you can put the .*
into the negative assertion directly:
/hello(?!.*my name is).*bob/
That'll keep the two from competing.
Upvotes: 1