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:
/(?<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 |
CodePudding user response:
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 )