Regex that matches not when string is duplicated

Viewed 35

I want to write a regular expression, that matches
foo
but not
foofoo

I tried to go with foo(?!foo) but this matches the the second foo in foofoo.
How can i modify this regex go only match foo but not foofoo.

1 Answers

If foo is a complete word then use word boundaries:

\bfoo\b

If it is in the middle of a word then use a negative lookahead and lookbehind;

(?<!foo)foo(?!foo)

RegEx Demo

Here:

  • (?<!foo): Assert that we don't have foo at previous position
  • foo: Match text foo
  • (?!foo): Assert that we don't have foo ahead
Related