Search code examples
regexpcre

Test strings that contain a specific pattern unless another pattern is before it


I want to test a string that contains the pattern \[[A-Z]+\].

But if there's a -- before it, the string should not pass.

Pass

  • [GET] test
  • test [POST] test
  • test [POST] --test
  • test [GET] test --test [DELETE] test

Even there's a -- before [DELETE], but there's no -- before [GET] so it still counts

Fail

  • test test
  • --[GET] test
  • test --[GET] test
  • test --test [PUT] test

I tried ^(?!.*--.*\[[A-Z]+\]).*\[[A-Z]+\] but it fails test [GET] test --test [DELETE] test

Here's a project on Regex101

Is there a regex can test this?


Solution

  • You may use this regex:

    ^(?:(?!--).)*\[[A-Z]+\]
    

    RegEx Demo

    RegEx Details:

    • ^: Start
    • (?:: Start non-capture group
      • (?!--): Negative lookahead to assert that we don't have --
      • .: Match any character
    • )*: End non-capture group. Match 0 or more of this group
    • \[[A-Z]+\]: Match [ followed by upper case followed by ]

    Alternatively you may also use this regex with PCRE verbs (*SKIP)(*FAIL):

    --.*(*SKIP)(*F)|\[[A-Z]+\]
    

    RegEx Demo 2