0

I want to create regular expression to validate US phone numbers, which will validate below need:

333 (till 1 to 3 digits)
333-3 (3 digits + 1 hyphen + 1 to 3 digit)
333-333-3333 (3 digits + 1 hyphen + 3 digit + 1 hyphen + 1 to 4 digits)
333-333-3333 3333 (3 digits + 1 hyphen + 3 digit + 1 hyphen + 4 digits + 1 space + 1 to 4 digits)
33333333333333 (any number of digit between 1 to 14)

I started regular expression from:

^\d{0-3}-\d{3}-\d{4}\s\d{4}$

Here I only want to validate above conditions, No special characters are allowed. I don't want to be generic. Only need to follow above conditions. Thanks in advance.

Rohit Sonaje
  • 522
  • 4
  • 14
  • possible duplicate of [A comprehensive regex for phone number validation](http://stackoverflow.com/questions/123559/a-comprehensive-regex-for-phone-number-validation) – Michel Jun 18 '15 at 08:37

2 Answers2

0

You already described it, just translate that into a rexgex:

^\d{1,14}$       |         # (any number of digit between 1 to 14)
^\d{3}-\d{1,3}$  |         # (3 digits + 1 hyphen + 1 to 3 digit)
^\d{3}-\d{1,3}-\d{1,4}$  | # (3 digits + 1 hyphen + 1 to 3 digit + 1 hyphen + 1 to 4 digits)
^\d{3}-\d{1,3}-\d{1,4}\s\d{1,4}$ # (3 digits + 1 hyphen + 1 to 3 digit + 1 hyphen + 1 to 4 digits + 1 space + 1 to 4 digits)

Demo

dawg
  • 98,345
  • 23
  • 131
  • 206
0

Thanks for the Help.

I have created below regex for above requirement, and it works for me.

^\d{0,3}$|^\d{3}-\d{1,3}$|^\d{3}-\d{3}-\d{1,4}$|^\d{3}-\d{3}-\d{4}\s{1}\d{1,4}$|^\d{1,14}$
Rohit Sonaje
  • 522
  • 4
  • 14