Regex for matching certain numbers of digits

/[^\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?


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


This regex would do

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

or if you dont want to match it exactly

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