Regex for matching certain numbers of digits

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

Leave a Comment