正则表达式如何匹配可选字符 [英] Regex how to match an optional character

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

问题描述

我有一个正则表达式,我以为到现在为止都可以正常工作.我需要匹配一个可选字符.它可能在那里,也可能不在那里.

I have a regex that I thought was working correctly until now. I need to match on an optional character. It may be there or it may not.

这是两个字符串.顶部的字符串匹配,而下部的字符串不匹配.低位字符串中没有单个字母是导致失败的原因.

Here are two strings. The top string is matched while the lower is not. The absence of a single letter in the lower string is what is making it fail.

如果要在开头的5位数字之后得到一个字母,如果不是,请继续获取字符串的其余部分.该字母可以是A-Z.

I'd like to get the single letter after the starting 5 digits if it's there and if not, continue getting the rest of the string. This letter can be A-Z.

如果我从正则表达式中删除([A-Z]{1}) +.*? +,它将匹配我需要的除字母之外的所有内容,但这很重要.

If I remove ([A-Z]{1}) +.*? + from the regex, it will match everything I need except the letter but it's kind of important.

20000      K               Q511195DREWBT            E00078748521
30000                      K601220PLOPOH            Z00054878524

这是我正在使用的正则表达式.

Here is the regex I'm using.

/^([0-9]{5})+.*? ([A-Z]{1}) +.*? +([A-Z]{1})([0-9]{3})([0-9]{3})([A-Z]{3})([A-Z]{3}) +([A-Z])[0-9]{3}([0-9]{4})([0-9]{2})([0-9]{2})/

推荐答案

使用

[A-Z]?

使字母可选. {1}是多余的. (当然,您也可以写[A-Z]{0,1},意思是一样的,但这就是?的用途.)

to make the letter optional. {1} is redundant. (Of course you could also write [A-Z]{0,1} which would mean the same, but that's what the ? is there for.)

您可以将正则表达式改进为

You could improve your regex to

^([0-9]{5})+\s+([A-Z]?)\s+([A-Z])([0-9]{3})([0-9]{3})([A-Z]{3})([A-Z]{3})\s+([A-Z])[0-9]{3}([0-9]{4})([0-9]{2})([0-9]{2})

而且,由于在大多数正则表达式中,\d[0-9]相同:

And, since in most regex dialects, \d is the same as [0-9]:

^(\d{5})+\s+([A-Z]?)\s+([A-Z])(\d{3})(\d{3})([A-Z]{3})([A-Z]{3})\s+([A-Z])\d{3}(\d{4})(\d{2})(\d{2})

但是:您真的需要11个单独的捕获组吗?如果是这样,为什么不捕获倒数第四组数字呢?

But: do you really need 11 separate capturing groups? And if so, why don't you capture the fourth-to-last group of digits?

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

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