Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression for 2 or 5 digits

Tags:

regex

How do I write a regular expression that can match only numbers with 2 or 5 digits?

I have this so far but it matches any number with 2 to 5 digits.

           ^\d{2,5}$
like image 719
RKodakandla Avatar asked Oct 26 '12 15:10

RKodakandla


1 Answers

Use 3 optional digits:

^\d{2}\d{3}?$

Note that some regex engines will interpret the ? after any repetition modifier (even a fixed one) as an ungreedy modifier, which seems to cause problems for the case of two digits. If you experience this, use:

^\d{2}(?:\d{3})?$

You can read up on some regex basics in this great tutorial.

By the way, the above is effectively equivalent (but marginally more efficient) to this one using alternation:

^(?:\d{2}|\d{5})$

(Just for the sake of showing you another regex concept.)

like image 122
Martin Ender Avatar answered Oct 25 '22 17:10

Martin Ender