2

I wrote this regex to identify US type phone numbers:

\(?\d{3}\)?(-|\s)\d{3}-\d{4}

This works for phone numbers like:

217-244-2424 and (217) 244-2424.

However it also works for unbalanced parenthesis like (217-244-2424

How can the regex be improved to make sure the parenthesis are balanced? (I'm aware of the questions on regex phone numbers asked before, but I couldn't find what I was looking for from there.)

Community
  • 1
  • 1
user2063763
  • 167
  • 1
  • 1
  • 4

2 Answers2

2

I will answer you specific question on regex. You can try something like this to handle paranthesis:

^(\(\d{3}\)|\d{3})-(\d{3})-(\d{4})$
manojlds
  • 290,304
  • 63
  • 469
  • 417
0

I have not tested it, but why not using the alternation operator ("|")? You could choose to have either both parenthesis, or none of them:

(\(\d{3}\)|\d{3})(-|\s)\d{3}-\d{4}
JonasVautherin
  • 7,297
  • 6
  • 49
  • 95