Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
457 views
in Technique[技术] by (71.8m points)

regex - Regular expression to match standard 10 digit phone number

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})sd{3}-d{4}
^[1-9]d{2}sd{3}sd{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.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
^(+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?1s)?(?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}$

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...