[英]Simple phone number regex for php
I've been looking for a simple phone number regex that will match just this format: (XXX) XXX-XXXX <---with the parentheses and the space after them required我一直在寻找一个简单的电话号码正则表达式,它只会匹配以下格式: (XXX) XXX-XXXX <--- 需要括号和空格
For the life of me, I can't figure out why this wont work (This was one that I tried making myself and have been tinkering with for hours):对于我的生活,我无法弄清楚为什么这行不通(这是我自己尝试制作的并且已经修补了几个小时):
^[\(0-9\){3} [0-9]{3}-[0-9]{4}$
I've looked everywhere online for a regex with that particular format matching to no avail.我在网上到处寻找具有该特定格式匹配的正则表达式,但无济于事。 Please help?请帮忙?
The following regex works以下正则表达式有效
^\(\d{3}\) \d{3}-\d{4}$
^ = start of line
\( = matches parenthesis open
\d = digit (0-9)
\) = matches parenthesis close
here's a working one这是一个工作的
/^\(\d{3}\) \d{3}-\d{4}\s$/
the problems with your's:你的问题:
to match digits just use \\d
or [0-9]
(square brackets are needed, you've forgot them in first occurence) to match parenthesis use \\(
and \\)
.匹配数字只需使用\\d
或[0-9]
(需要方括号,您在第一次出现时忘记了它们)来匹配括号使用\\(
和\\)
。 They have to be escaped, otherwise they will be interpreted as match and your regex won't compile它们必须被转义,否则它们将被解释为匹配并且您的正则表达式将无法编译
The problems you are having are:您遇到的问题是:
\\(
您需要使用反斜杠转义特殊字符(如括号),如下所示: \\(
Otherwise, you're good!否则,你很好!
[]
define character classes. []
定义字符类。 eg "at this one single character spot, any of the following can match".例如“在这个单个字符的位置,以下任何一个都可以匹配”。 Your brackets are misaligned:您的括号未对齐:
^[\(0-9\){3} [0-9]{3}-[0-9]{4}$
^---no matching closer
eg例如
^[0-9]{3} [0-9]{3}-[0-9]{4}$
would be closer to what you want.会更接近你想要的。
/(\(\d{3}+\)+ \d{3}+\-\d{4}+)/ (000) 000-0000
/(\d{3}+\-\d{3}+\-\d{4}+)/ 000-000-0000
EDITED ^\\(?\\d{3}\\)?\\s?\\-?\\d{3}\\s?\\-?\\d{4}$
编辑^\\(?\\d{3}\\)?\\s?\\-?\\d{3}\\s?\\-?\\d{4}$
in Php works for the following在 PHP 中适用于以下内容
(999) 999 9999 (999) 999 9999
(999) 999-9999 (999) 999-9999
(999) 999-9999 (999) 999-9999
999 999 9999 999 999 9999
999 999-9999 999 999-9999
999-999-9999 999-999-9999
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.