Home > Software design >  Regex match only if a string is not present
Regex match only if a string is not present

Time:04-05

I want to match in regex if a particular string is not present, for eg: the regex should match when the string is :

"pool" "pool play" "poolplay"

and not match when the string is :

"car pool" "car pool play"

i was using something like: (?i)(pool(e|ed|ing)*)^(car pool(e|ed|ing)*) but need some help in perfecting it

CodePudding user response:

You can use

(?i)(?<!\bcar\s)pool(?:ed?|ing)?

See the regex demo. Add the word boundary \b after (?i) if the word you want to match starts with pool.

In Java, you can define the pattern with the following string literal:

String regex = "(?i)(?<!\\bcar\\s)pool(?:ed?|ing)?";

Details:

  • (?i) - case insensitive matching on
  • (?<!\bcar\s) - no car as whole word whitespace allowed immediately on the left
  • pool - a pool substring
  • (?:ed?|ing)? - an optional e, ed or ing char sequence.
  • Related