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}$
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Use 3 optional digits:
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: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:
(Just for the sake of showing you another regex concept.)