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.


Solution 1:

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

 Tom(?!\s+Thumb)

Solution 2:

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.

Solution 3:

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