Need Code for US Phone numbers using Dashes or Parentheses but not spaces

54 views Asked by At

I am new to RegEx and need some guidance. Right now I have the following validation for phone numbers:

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

Unfortunately, the system I am importing the results into does not think favorably of the numbers being separated solely by spaces or not separated at all. What would the formula look like that requires either dashes or parentheses and accepts only the following formats: XXX-XXX-XXXX or (XXX) XXX-XXXX?

Thank you for your assistance.

1

There are 1 answers

1
duffymo On

Start simple:

\d{3}-\d{3}-\d{4} works beautifully for numbers like 212-867-5309.

As for others, I'd say you and your users would be better off if you kept it simple. No switching, no choices. Pick a standard. Simple is good.

If you must persist, look at this web site for help. You aren't the first.