正则表达式可选组 [英] Regex optional group

查看:77
本文介绍了正则表达式可选组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用此正则表达式:

I am using this regex:

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

匹配这样的字符串:

SH_6208069141055_BC000388_20110412101855

分为4组:

SH
6208069141055
BC000388
20110412101855

问题:如何将第一个组设为可选,以使生成的组为空字符串?
我希望在任何情况下都尽可能地分成4组.

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

推荐答案

您可以轻松地将正则表达式简化为:

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演示

如您所见,第二个匹配项中的匹配组1为空,从匹配组2开始.

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

这篇关于正则表达式可选组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆