user1116377 user1116377 - 7 months ago 11
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



thanks

Answer

You can use this lookaheads regex:

^(?!.*\(\[(?:(?!\(\[|\]\)).)*TEST(?:(?!\(\[|\]\)).)*\]\))(?=.*TEST).*
  • (?!..) 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