正则表达式模式可选字符 [英] Regexp pattern Optional character

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

问题描述

我想匹配像 19740103-0379 或 197401030379 这样的字符串,即破折号是可选的.如何使用正则表达式完成此操作?

I want to match a string like 19740103-0379 or 197401030379, i.e the dash is optional. How do I accomplish this with regexp?

推荐答案

通常你可以使用 -?.或者,您可以使用 -{0,1} 但您应该发现 ? 几乎在任何地方都支持零次或一次出现".

Usually you can just use -?. Alternatively, you can use -{0,1} but you should find that ? for "zero or one occurrences of" is supported just about everywhere.

pax> echo 19740103-0379 | egrep '19740103\-?0379'
19740103-0379

pax> echo 197401030379 | egrep '19740103\-?0379'
197401030379

如果您想在任何地方接受带有任意数量破折号的 12 位数字,您可能需要执行以下操作:

If you want to accept 12 digits with any number of dashes in there anywhere, you might have to do something like:

-*([0-9]-*){12}

基本上是零个或多个破折号后跟 12 次出现(一个数字后跟零个或多个破折号),并将捕获各种精彩内容,例如:

which is basically zero or more dashes followed by 12 occurrences of (a digit followed by zero or more dashes) and will capture all sorts of wonderful things like:

--3-53453---34-4534---

(当然,如果您的正则表达式引擎支持,您应该使用 \d 而不是 [0-9]).

(of course, you should use \d instead of [0-9] if your regex engine has support for that).

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

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