Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading