Jørgen
Jørgen

Reputation: 9130

Regex for matching certain numbers of digits

The following regex will match the range 9-11 digits: /\d{9,11}/

What is the best way to write a regex matching exactly 9 or 11 digits (excluding 10)?

Using the pattern attribute of an input element, thus the regex should match the entire value of the input field. I want to accept any number containing 9 or 11 digits.

Upvotes: 47

Views: 95396

Answers (3)

Anirudha
Anirudha

Reputation: 32787

This regex would do

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

or if you dont want to match it exactly

\D(\d{9}|\d{11})\D

Upvotes: 7

itsbruce
itsbruce

Reputation: 4843

/[^\d](\d{9}|\d{11})[^\d]/

Depending on which tool you are using, you may need to escape the (, | and ) characters.

Note that in order to not match 8, or any other number other than 9 or 11, the regex must be bounded with something to indicate that the match is surrounded by non-digit characters. Ideally, it would be some kind of word-boundary character, but the syntax for that would vary depending on the tool.

/\b(\d{9}|\d{11})\b/

works with some tools. What are you working with?

Upvotes: 2

paxdiablo
paxdiablo

Reputation: 881263

Well, you could try something like:

^\d{9}(\d{2})?$

This matches exactly nine digits followed by an optional extra-two-digits (i.e., 9 or 11 digits).

Alternatively,

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

may work as well.

But remember that not everything necessarily has to be done with regular expressions. It may be just as easy to check the string matches ^\d*$ and that the string length itself is either 9 or 11 (using something like strlen, for example).

Upvotes: 53

Related Questions