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.

https://stackoverflow.com/questions/66908921/

相关文章:

c++ - 如果 new 运算符失败,是否可以将指针设置为 null?

ios - React native Pod 安装得到权限被拒绝

git - 使用 git rev-parse 的错误提交哈希

reactjs - 配置多个下一个插件 : withMDX, withBundleAnalyzer

javascript - 使用 filter() 而不是 map() 来修改对象数组?

postgresql - 我想用 mikro-orm 插入,但它找不到我的表 :c (TableNo

.net-core - Cake Clean 任务在蛋糕构建时被跳过

c++ - 为什么C++语言的malloc函数前面要写指针类型?

email - SendGrid Automated Security 如何处理 SPF 记录?

html - 将样式添加到 mat-autocomplete 的 mat-option