Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to match a digit two or four times

Tags:

regex

numbers

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.

like image 211
Renato Dinhani Avatar asked Nov 18 '11 02:11

Renato Dinhani


People also ask

How does regex match 4 digits?

Add the $ anchor. /^SW\d{4}$/ . It's because of the \w+ where \w+ match one or more alphanumeric characters. \w+ matches digits as well.

Which regex matches one or more digits?

Occurrence Indicators (or Repetition Operators): +: one or more ( 1+ ), e.g., [0-9]+ matches one or more digits such as '123' , '000' . *: zero or more ( 0+ ), e.g., [0-9]* matches zero or more digits. It accepts all those in [0-9]+ plus the empty string.

How do I match a number in regex?

To match any number from 0 to 9 we use \d in regex. It will match any single digit number from 0 to 9. \d means [0-9] or match any number from 0 to 9. Instead of writing 0123456789 the shorthand version is [0-9] where [] is used for character range.

How do I match a pattern in regex?

Regular expressions, called regexes for short, are descriptions for a pattern of text. For example, a \d in a regex stands for a digit character — that is, any single numeral 0 to 9. Following regex is used in Python to match a string of three numbers, a hyphen, three more numbers, another hyphen, and four numbers.


1 Answers

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

like image 66
ruakh Avatar answered Oct 20 '22 22:10

ruakh