正则表达式匹配一个数字两次或四次 [英] Regex to match a digit two or four times

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

问题描述

这是一个关于正则表达式的简单问题,但我没有找到答案.

It's a simple question about regular expressions, but I'm not finding the answer.

我想确定一个数字是否恰好按两次四次的顺序出现.我可以使用什么语法?

I want to determine whether a number appears in sequence exactly two or four times. What syntax can I use?

\d{这里有什么?}

我试过 \d{2,4},但这个表达式也接受三位数字.

I tried \d{2,4}, but this expression accepts three digits as well.

推荐答案

没有具体的语法,但有很多方法可以做到:

There's no specific syntax for that, but there are lots of ways to do it:

(?:\d{4}|\d{2})    <-- alternation: four digits if possible, else just two
\d{2}(?:\d{2})?    <-- two digits, plus two more if possible
(?:\d{2}){1,2}     <-- two digits, times one or two

因此,例如,要匹配由一个或多个字母 A–Z 后跟两个或四个数字组成的字符串,您可以编写 ^[AZ]+(?:\d{4}|\d{2})$;并匹配以逗号分隔的两位或四位数字列表,您可以编写 ^((?:\d{4},|\d{2},)*(?:\d{4}|\d{2})$^(?:\d{2}(?:\d{2})?,)*\d{2}(?:\d{2})$.

So, for example, to match strings consisting of one or more letters A–Z followed by either two or four digits, you might write ^[A-Z]+(?:\d{4}|\d{2})$; and to match a comma-separated list of two-or-four-digit numbers, you might write ^((?:\d{4},|\d{2},)*(?:\d{4}|\d{2})$ or ^(?:\d{2}(?:\d{2})?,)*\d{2}(?:\d{2})$.

这篇关于正则表达式匹配一个数字两次或四次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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