Home > Net >  How can I use regex to match a string with several ending values including no end value?
How can I use regex to match a string with several ending values including no end value?

Time:06-14

I'm trying to come up with with a regex statement that will match and not match the following cases:

CT.test                  // (1) must match
CT.test (MONT)           // (2) must match
CT.test (ABS)            // (3) must match
CT.badsf                 // (4) must not match
CT.test (WOW)            // (5) must not match

I've tried CT.test( \(MONT\)| \(ABS\)|^$) but that only matches cases 2 and 3 and not case 1.

What is a regex statement that will match case 1, 2 and 3 and not match cases 4 and 5?

CodePudding user response:

You can use

^CT\.test(?: \((?:MONT|ABS)\))?$

See the regex demo

See the details here:

  • ^ - start of string
  • CT\.test - (note the escaped dot): a CT.test string
  • (?: \((?:MONT|ABS)\))? - an optional sequence of
    • - a space
    • \( - a ( char
    • (?:MONT|ABS) - MONT or ABS string
    • \) - a ) char
  • $ - end of string.
  • Related