Regex to match a digit two or four times

Renato Dinhani picture Renato Dinhani · Nov 18, 2011 · Viewed 86.2k times · Source

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.

Answer

ruakh picture ruakh · Nov 18, 2011

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

(?:\d{4}|\d{2})    <-- alternation: four digits or two
\d{2}(?:\d{2})?    <-- two digits, and optionally two more
(?:\d{2}){1,2}     <-- two digits, times one or two