254 shaares
1 result
tagged
regex
I'm trying to write a regular expression to validate US phone number of format (123)123-1234 or 123-123-1234 as true.
The easiest way to match both this (000)000-0000 is this
^\([0-9]{3}\)[0-9]{3}-[0-9]{4}$
and this 000-000-0000 is this
^[0-9]{3}-[0-9]{3}-[0-9]{4}$
and to use alternation ((...|...)): specify them as two mostly-separate options:
^(\([0-9]{3}\)|[0-9]{3}-)[0-9]{3}-[0-9]{4}$
By the way, when Americans put the area code in parentheses, we actually put a space after that; for example, I'd write (123) 123-1234, not (123)123-1234. So you might want to write:
^(\([0-9]{3}\) |[0-9]{3}-)[0-9]{3}-[0-9]{4}$
(Though it's probably best to explicitly demonstrate the format that you expect phone numbers to be in.)
The easiest way to match both this (000)000-0000 is this
^\([0-9]{3}\)[0-9]{3}-[0-9]{4}$
and this 000-000-0000 is this
^[0-9]{3}-[0-9]{3}-[0-9]{4}$
and to use alternation ((...|...)): specify them as two mostly-separate options:
^(\([0-9]{3}\)|[0-9]{3}-)[0-9]{3}-[0-9]{4}$
By the way, when Americans put the area code in parentheses, we actually put a space after that; for example, I'd write (123) 123-1234, not (123)123-1234. So you might want to write:
^(\([0-9]{3}\) |[0-9]{3}-)[0-9]{3}-[0-9]{4}$
(Though it's probably best to explicitly demonstrate the format that you expect phone numbers to be in.)