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

Regex to capture optional characters

I want to pull out a base string (Wax) from a longer string, along with some data before and after. I’m having trouble getting the last item in my list below (noWax) to match.

Can anyone flex their regex muscles? I’m fairly new to regex so advice on optimization is welcome as long as all matches below are found.

What I’m working with in Regex101:

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


/(?<Wax>Wax(?:Only|-?\d+))/mg

Original string need to extract in a capturing group
Loc3_341001_WaxOnly_S212 WaxOnly
Loc4_34412-a_Wax4_S231 Wax4
Loc3a_231121-a_Wax-4-S451 Wax-4
Loc3_34112_noWax_S311 noWax

>Solution :

Here is one way to do so, using a conditional:

(?<Wax>(no)?Wax(?(2)|(?:Only|-?\d+)))

See the online demo.


  • (no)?: Optional capture group.
  • (? If.
    • (2): Test if capture group 2 exists ((no)). If it does, do nothing.
    • |: Or.
    • (?:Only|-?\d+)
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