正则表达式验证美国电话号码?

问题描述:


可能重复:

用于电话号码验证的全面正则表达式

使用JavaScript验证电话号码

我正在尝试写一个正则表达式来验证美国电话号码格式
(123)123-1234 - 真
123-123-1234 - 真

I'm trying to write a regular expression to validate US phone number of format (123)123-1234 -- true 123-123-1234 -- true

其他所有的东西都无效。

every thing else in not valid.

我想出的东西像

 ^\(?([0-9]{3}\)?[-]([0-9]{3})[-]([0-9]{4})$

但是这个验证,
123)-123-1234
(123-123-1234

But this validates, 123)-123-1234 (123-123-1234

这是不对的。

最简单的匹配方式两个

^\([0-9]{3}\)[0-9]{3}-[0-9]{4}$

^[0-9]{3}-[0-9]{3}-[0-9]{4}$

是使用交替(... | ...)):将它们指定为两个主要分开的选项:

is to use alternation ((...|...)): specify them as two mostly-separate options:

^(\([0-9]{3}\)|[0-9]{3}-)[0-9]{3}-[0-9]{4}$

顺便说一句,当美国人把区号放在括号中时,我们实际上在那之后放了一个空格;例如,我写(123)123-1234 ,而不是(123)123-1234 。所以你可能想写:

By the way, when Americans put the area code in parentheses, we actually put a space after that; for example, I'd write (123) 123-1234, not (123)123-1234. So you might want to write:

^(\([0-9]{3}\) |[0-9]{3}-)[0-9]{3}-[0-9]{4}$

(虽然最好明确说明您希望电话号码所在的格式。)

(Though it's probably best to explicitly demonstrate the format that you expect phone numbers to be in.)