Regex optional group

戏子无情 提交于 2019-12-18 18:38:22

问题


I am using this regex:

((?:[a-z][a-z]+))_(\d+)_((?:[a-z][a-z]+)\d+)_(\d{13})

to match strings like this:

SH_6208069141055_BC000388_20110412101855

separating into 4 groups:

SH
6208069141055
BC000388
20110412101855

Question: How do I make the first group optional, so that the resulting group is a empty string?
I want to get 4 groups in every case, when possible.

Input string for this case: (no underline after the first group)

6208069141055_BC000388_20110412101855

回答1:


You can easily simplify your regex to be this:

(?:([a-z]{2,})_)?(\d+)_([a-z]{2,}\d+)_(\d+)$

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.



来源:https://stackoverflow.com/questions/18633334/regex-optional-group

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!