Regex optional group

You can easily simplify your regex to be this:

(?:([a-z]{2,})_)?(\d+)_([a-z]{2,}\d+)_(\d+)$
^              ^^
|--------------||
| first group  ||- quantifier for 0 or 1 time (essentially making it optional) 

I’m not sure whether the input string without the first group will have the underscore or not, but you can use the above regex if it’s the whole string.

regex101 demo

As you can see, the matched group 1 in the second match is empty and starts at matched group 2.

Leave a Comment

tech