1

I'm using /^\d{3}\ ?-? ?\d{3}\ ?-? ?\d{4}$/; to validate US phone numbers. Can anyone tell me how to modify this expression to make () optional on the first set of numbers.

For example: it should work for (123)234-2345 , 123-345-4567 , 123 - 345 - 4567 , 123345-6789

2 Answers 2

2

Area code with or without braces

(?:\(\d{3}\)|\d{3})

optional - with optional spaces around it

(?: *- *)?

3 digits

\d{3}

and 4 digits

\d{4}

and all together now

^(?:\(\d{3}\)|\d{3})(?: *- *)?\d{3}(?: *- *)?\d{4}$
Sign up to request clarification or add additional context in comments.

3 Comments

@melpomene Thanks for this hint, fixed.
@melpomene Ouch, embarrassing :$
@melpomene I hope, I'm old enough to stick with it ;-)
0
/^\(?\d{3}\)? ?-? ?\d{3} ?-? ?\d{4}$/

4 Comments

after your second d{3} '\' is missing
No, there is no \ missing. Why are you asking me about your expression instead of trying my answer?
Because mine and yours is same except the '\'
No, it isn't. Mine doesn't contain ^(?.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.