Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex: optional group

Tags:

regex

I want to split a string like this:

abc//def//ghi

into a part before and after the first occurrence of //:

a: abc
b: //def//ghi

I'm currently using this regex:

(?<a>.*?)(?<b>//.*)

Which works fine so far.

However, sometimes the // is missing in the source string and obviously the regex fails to match. How is it possible to make the second group optional?

An input like abc should be matched to:

a: abc
b: (empty)

I tried (?<a>.*?)(?<b>//.*)? but that left me with lots of NULL results in Expresso so I guess it's the wrong idea.

like image 484
mafu Avatar asked Oct 21 '25 14:10

mafu


1 Answers

Try a ^ at the begining of your expression to match the begining of the string and a $ at the end to match the end of the string (this will make the ungreedy match work).

^(?<a>.*?)(?<b>//.*)?$
like image 190
stevehipwell Avatar answered Oct 23 '25 03:10

stevehipwell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!