user1364539
user1364539

Reputation: 601

RegExp exclusion, looking for a word not followed by another

I am trying to search for all occurrences of "Tom" which are not followed by "Thumb".

I have tried to look for

Tom ^((?!Thumb).)*$

but I still get the lines that match to Tom Thumb.

Upvotes: 60

Views: 30475

Answers (3)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626794

In case you are not looking for whole words, you can use the following regex:

Tom(?!.*Thumb)

If there are more words to check after a wanted match, you may use

Tom(?!.*(?:Thumb|Finger|more words here))
Tom(?!.*Thumb)(?!.*Finger)(?!.*more words here)

To make . match line breaks please refer to How do I match any character across multiple lines in a regular expression?

See this regex demo

If you are looking for whole words (i.e. a whole word Tom should only be matched if there is no whole word Thumb further to the right of it), use

\bTom\b(?!.*\bThumb\b)

See another regex demo

Note that:

  • \b - matches a leading/trailing word boundary
  • (?!.*Thumb) - is a negative lookahead that fails the match if there are any 0+ characters (depending on the engine including/excluding linebreak symbols) followed with Thumb.

Upvotes: 37

alan
alan

Reputation: 4842

You don't say what flavor of regex you're using, but this should work in general:

 Tom(?!\s+Thumb)

Upvotes: 55

noob
noob

Reputation: 9202

Tom(?!\s+Thumb) is what you search for.

Upvotes: 1

Related Questions