我想编写一个正则表达式来匹配以下格式的电话号码,即
1- 无国家代码 9999999999
2 - 1 位国家代码 +19999999999
3 - 带国家代码和 () +1(999)9999999
4 - 带国家代码 () 和 - +1(999)-999-9999
我写了一个匹配条件 2 但在 1,3 和 4 中失败的正则表达式。
^[\+]?[(]?[0-9]{3}[)]?[-\s\.]?[0-9]{3}[-\s\.]?[0-9]{4,6}$
一旦我在 + 符号后添加国家代码以及 () 和 - 我的正则表达式就停止工作。
我该如何解决?我不是正则表达式专业人士,而是通过尝试通过谷歌搜索获得的不同模式来组装我的正则表达式。
如有任何帮助,我们将不胜感激。
最佳答案
编辑:由于 OP 已添加电话号码示例以与 + 号匹配,因此现在添加以下答案。
^(?:\d{10})?(?:\+)?(?:(?:\d{11})?(?:\d\(\d{3}\))?(?:(?:\d{7})?(?:-\d{3}-\d{4})?))$
Here is Online demo for above regex
根据您展示的示例,您能否尝试以下操作。
^\+(?:(?:\d{11})?(?:\d\(\d{3}\))?(?:(?:\d{7})?(?:-\d{3}-\d{4})?))$
Here is Online demo for above regex
说明: 为以上添加详细说明。
^\+ ##Checking if starting is from + sign.
(?: ##Starting a non-capturing group from here.
(?:\d{11})? ##Starting a non-capturing group which matches 11 digits here, keeping it optional.
(?:\d\(\d{3}\))? ##Starting a non-capturing group which matches single digit followed by ( 3 digits followed by ) and keeping this optional too.
(?: ##Starting a non-capturing group here.
(?:\d{7})? ##Starting a non-capturing group here with 7 digits keeping it optional.
(?:-\d{3}-\d{4})? ##Starting a non-capturing group which has - 3 digits - 4 digits keep it optional.
) ##Closing above non-capturing group here.
)$ ##Closing very first non-capturing group here.
关于regex - 为电话号码编写正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66908921/