Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression to match standard 10 digit phone number

Tags:

regex

I want to write a regular expression for a standard US type phone number that supports the following formats:

###-###-#### (###) ###-#### ### ### #### ###.###.#### 

where # means any number. So far I came up with the following expressions

^[1-9]\d{2}-\d{3}-\d{4} ^\(\d{3}\)\s\d{3}-\d{4} ^[1-9]\d{2}\s\d{3}\s\d{4} ^[1-9]\d{2}\.\d{3}\.\d{4} 

respectively. I am not quite sure if the last one is correct for the dotted check. I also want to know if there is any way I could write a single expression instead of the 4 different ones that cater to the different formats I mentioned. If so, I am not sure how do I do that. And also how do I modify the expression/expressions so that I can also include a condition to support the area code as optional component. Something like

+1 ### ### #### 

where +1 is the area code and it is optional.

like image 248
noobcoder Avatar asked May 22 '13 18:05

noobcoder


People also ask

How can I get 10 digit mobile number in C#?

Using a Regular Expression, we can validate a TextBox with 10 digit mobile number in C#. When asking a user to enter a mobile number, we usually validate if a number has 10 digits or not. If not, we ask user to enter full mobile number. In this case, I've a TextBox control on an ASP.NET Form.

Which regex matches one or more digits?

+: one or more ( 1+ ), e.g., [0-9]+ matches one or more digits such as '123' , '000' . *: zero or more ( 0+ ), e.g., [0-9]* matches zero or more digits. It accepts all those in [0-9]+ plus the empty string.


1 Answers

^(\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]\d{3}[\s.-]\d{4}$ 

Matches the following

123-456-7890 (123) 456-7890 123 456 7890 123.456.7890 +91 (123) 456-7890 

If you do not want a match on non-US numbers use

^(\+0?1\s)?\(?\d{3}\)?[\s.-]\d{3}[\s.-]\d{4}$ 

Update :
As noticed by user Simon Weaver below, if you are also interested in matching on unformatted numbers just make the separator character class optional as [\s.-]?

^(\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}$ 
like image 129
Ravi K Thapliyal Avatar answered Sep 20 '22 21:09

Ravi K Thapliyal