Reputation: 167
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.)
Upvotes: 2
Views: 61
Reputation: 8033
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}
Upvotes: 0
Reputation: 301087
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})$
Upvotes: 2