Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
624 views
in Technique[技术] by (71.8m points)

numbers - Regex to match a digit two or four times

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{what goes here?}

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...