匹配美国电话号码的正则表达式 [英] Regular expression to match US phone numbers

查看:116
本文介绍了匹配美国电话号码的正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正则表达式^((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}$匹配 XXX-XXX-XXXXXXX-XXXX 形式的字符串(我错过了什么?).

The regular expression ^((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}$ matches strings of the form XXX-XXX-XXXX and XXX-XXXX (am I missing out something?).

然而,它不匹配 (XXX) XXX-XXXX(XXX) XXX-XXX-XXXX (我需要它匹配).

It doesn't, however, match (XXX) XXX-XXXX and (XXX) XXX-XXX-XXXX as well (which I need it to match).

你能帮我修复它以匹配格式吗
XXX-XXX-XXXX,XXX-XXXX,(XXX) XXX-XXXX,(XXX) XXX-XXXX
不会导致它匹配我不想要的其他字符串格式?

Can you help me fix it so that it matches the formats
     XXX-XXX-XXXX, XXX-XXXX, (XXX) XXX-XXXX, (XXX) XXX-XXXX
without causing it to match other string formats which I don't want?

推荐答案

您的规范有点令人困惑.您的最后两个案例看起来相同:
XXX-XXX-XXXX
XXX-XXXX
(XXX) XXX-XXXX
(XXX)XXX-XXXX

Your specification is a bit confusing. Your last two cases appear the same:
XXX-XXX-XXXX
XXX-XXXX
(XXX) XXX-XXXX
(XXX) XXX-XXXX

(您似乎正在尝试匹配电话号码,对吗?)假设您的最后一个案例是(XXX)XXX-XXXX"(区号和常规号码之间没有空格,我假设是?"表示可选空格)那么您的 RegExp 几乎是正确的,只需在前面添加两个反斜杠区号括号,因此它们作为普通字符而不是特殊分组字符匹配:

<代码>^((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}$

(It looks like you're trying to match a phone number, is that right?) Assuming your last case is "(XXX)XXX-XXXX" (no space between area code and regular number, which I assume is the " ?" meaning optional space) then your RegExp is almost correct, just add two backslashes in front of the area code parentheses so they're matched as plain characters and not special grouping characters:

^((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}$

请注意,您的正则表达式可能没有正确通过,我注意到堆栈溢出从 RE 模式中删除了一个反斜杠,我必须键入一个双反斜杠\\"才能得到一个反斜杠在留言中

Note that your regular expression may not have come through correctly, I noticed that stack overflow removed a single backslash from the RE pattern, I had to type a double backslash "\\" in order to get a single backslash to come out in the message

这篇关于匹配美国电话号码的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆