Simple phone number regex for php

别等时光非礼了梦想. 提交于 2019-12-24 20:42:32

问题


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

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?


回答1:


The following regex works

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

^ = start of line
\( = matches parenthesis open
\d = digit (0-9)
\) = matches parenthesis close



回答2:


The problems you are having are:

  1. You need to escape special characters (like parentheses) with a backslash, like this: \(
  2. You have an unclosed square bracket at the beginning.

Otherwise, you're good!




回答3:


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 \). They have to be escaped, otherwise they will be interpreted as match and your regex won't compile




回答4:


[] define character classes. e.g. "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

e.g.

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

would be closer to what you want.




回答5:


/(\(\d{3}+\)+ \d{3}+\-\d{4}+)/ (000) 000-0000

/(\d{3}+\-\d{3}+\-\d{4}+)/ 000-000-0000


来源:https://stackoverflow.com/questions/13111295/simple-phone-number-regex-for-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!