0

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?

Anirudh Ramanathan
  • 46,179
  • 22
  • 132
  • 191
Joanne DeBiasa
  • 15
  • 1
  • 1
  • 6
  • well, that's actually not what I have. It's really /^\([0-9]\){3} [0-9]{3}-[0-9]{4}$/ – Joanne DeBiasa Oct 28 '12 at 17:39
  • OK, I guess it's taking out the backslashes that I had in it for some reason – Joanne DeBiasa Oct 28 '12 at 17:40
  • * See also [Open source RegexBuddy alternatives](http://stackoverflow.com/questions/89718/is-there) and [Online regex testing](http://stackoverflow.com/questions/32282/regex-testing) for some helpful tools, or [RegExp.info](http://regular-expressions.info/) for a nicer tutorial. – mario Oct 28 '12 at 17:41
  • Just so you know, i haven't personally written a phone number like `(###) ###-####` in maybe 10 years. Now that many phone services require or at least support entering the area code as part of the number, it seems a bit of a relic. `###-###-####` makes more sense. – cHao Oct 28 '12 at 17:54

6 Answers6

6

The following regex works

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

^ = start of line
\( = matches parenthesis open
\d = digit (0-9)
\) = matches parenthesis close
Anirudh Ramanathan
  • 46,179
  • 22
  • 132
  • 191
1

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

bukart
  • 4,906
  • 2
  • 21
  • 40
1

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!

Asad Saeeduddin
  • 46,193
  • 6
  • 90
  • 139
0

[] 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.

Marc B
  • 356,200
  • 43
  • 426
  • 500
0
/(\(\d{3}+\)+ \d{3}+\-\d{4}+)/ (000) 000-0000

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

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

in Php works for the following

(999) 999 9999

(999) 999-9999

(999) 999-9999

999 999 9999

999 999-9999

999-999-9999

user3251285
  • 153
  • 1
  • 8
  • What is the purpose of `?` after `\d{4}`. This regex is matching `(1234567890` or `123) -456 -7890`. – Toto Jun 09 '20 at 12:25