且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

正则表达式匹配一个数字两次或四次

更新时间:2022-12-09 18:39:14

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

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})$.