正则表达式匹配标准的 10 位电话号码 [英] 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}\)\s\d{3}-\d{4}
^[1-9]\d{2}\s\d{3}\s\d{4}
^[1-9]\d{2}\.\d{3}\.\d{4}
分别.我不太确定最后一个对于虚线检查是否正确.我还想知道是否有任何方法可以编写单个表达式而不是满足我提到的不同格式的 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 ### ### ####
其中 +1 是区号,它是可选的.
where +1 is the area code and it is optional.
推荐答案
^(\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]\d{3}[\s.-]\d{4}$
匹配以下内容
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}$
更新:
正如下面的用户 Simon Weaver 所注意到的,如果您也对匹配无格式数字感兴趣,只需将分隔符类设为可选的 [\s.-]?
^(\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}$
这篇关于正则表达式匹配标准的 10 位电话号码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!