问题
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:
- You need to escape special characters (like parentheses) with a backslash, like this:
\( - 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