user1116377 user1116377 - 2 years ago 89
Java Question

Regex - check if a substring is not part of a pattern

I would like to check in a given string that if the word TEST appears in the string then it is NOT inside the pattern ([]).
The regex should return true for the following example strings:

  • TEST

  • this is my ([TEST

  • this is my TEST]) number 2

  • ([bla]) TEST ([bla])

Should return false for the following example strings:

  • this is my ([TEST]) oops

  • this is my ([bla TEST bla])

  • this is my ([TEST TEST])

  • string without the tes* word


Answer Source

You can use this lookaheads regex:

  • (?!..) is negative lookahead to fail the match if ([..TEST..]) appears anywhere in the line.
  • (?=.*TEST) is positive lookahead to ensure that line contains TEST

RegEx Demo

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download