regex - 为电话号码编写正则表达式

标签 regex

我想编写一个正则表达式来匹配以下格式的电话号码,即

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/

相关文章:

regex - Perl 正则表达式用空格替换除 float 以外的所有内容

python - 重新拆分后的空格字符

JavaScript 判断 url 标签是否匹配

sql - 数据库表中的搜索模式

c# - 用 Razor 替换正则表达式函数

regex - 在正则表达式中搜索零到 n 和零到一

c# - C#在正则表达式中允许斜杠(和其他类似字符)

regex - 相当于chomp的正则表达式

Python 正则表达式匹配 C++ typedef'd 枚举

python - Python 正则表达式中的反斜杠字符