3

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

3
  • What about ([TEST TEST])? Does that match or not? Commented May 3, 2016 at 19:04
  • How about ([bla]) TEST ([bla])? Commented May 3, 2016 at 19:11
  • @svinja the regex should match for ([bla]) TEST ([bla]) since the pattern is closed before the TEST word. great catch. Commented May 3, 2016 at 19:16

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

7 Comments

it fails for ([bla]) [TEST]([bla])
That's not correct as ([bla]) [TEST]([bla]) comes as a match in the demo link.
sorry.. that's what I meant
it says that it's a match.. but for what I understood, it shouldn't point that as a match
@Hugo it should come as a match. anubhava thanks a lot!
|
3
/\[.*TEST.*\]/g

inverse of what you asked (see Regex101 demo), just do a '!' before match

3 Comments

You might want to change your answer slightly since the flavor has been established as Java. Conceptually, your answer is fine though.
could you please explain the '!' before match?
@user1116377 Invert the boolean that indicates if there is a match.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.