Tony
Tony

Reputation: 12695

How to match a 9 or 14 digits long number with regex?

I need to check by Regex expression if 9 or 14 digits are typed.

The expression \d{9}|\d{14} seems to be not working properly, what's wrong ?

Upvotes: 5

Views: 40531

Answers (3)

codaddict
codaddict

Reputation: 455072

You can use:

^(?:\d{9}|\d{14})$

Explanation:

^       - Start anchor
(?:     - Start of non-capturing group      
 \d{9}  - 9 digits
 |      - alternation
 \d{14} - 14 digits
)       - close of the group.
$       - End anchor

alternatively you can do:

^\d{9}(?:\d{5})?$

which matches 9 digits followed by optional 5 digits.

Upvotes: 9

Andrea Ambu
Andrea Ambu

Reputation: 39516

This regex should work.

^(\d{9}|\d{14})$

Could you post the piece of code you're using and tell us what language are you using? If you're using regex chances are that you have a string, and I'm sure your language has something to count string length.

EDIT:
as Rubens Farias pointed out in comments maybe ^...$ is needed because your regex would match any number with more than 9 digit as that number has a substring with a 9 digit long number.

Anyway check if you can do it with your language's string's methods/functions

Upvotes: 16

ennuikiller
ennuikiller

Reputation: 46965

(\d{9}|\d{14}) should work

Upvotes: -1

Related Questions