A simple regex I wrote to loosely validate phone number format. I want it to match a US/CAN phone number without being anal about it and alienating my users with a rigit format. It will match any of those:
- 1-800-555-5555
- 1 (800) 555-5555
- 1 555 555 5555
- 555-555-5555
- 555 555-5555
- 555 555 5555
- 555-5555
- 555 5555
- 1-800-555-5555 ext: 500
- 1-800-555-5555 #500
((\d{1})?([\s-])?(\()?(\d{3})?(\))?([\s-])?((\d{3})[\s-](\d{4}))(\s.+?\s?(\d{1,5}))?)
(
(\d{1})? # Country number
([\s-])? # Space or an hyphen
(\()? # Optional parenthesis around area code
(\d{3})? # Area code
(\))? # Closing parenthesis
([\s-])? # Space or hyphen
(
(\d{3}) # 3 first digits of the phone number
[\s-] # Space or hypen
(\d{4}) # Last 4 digits
)
(
\s # Space between phone number and extension
.+? # Anything between the phone number and extension (ext, ext:, #)
\s? # Space
(\d{1,5}) # Extension number, between 1 and 5 digits
)? # Make the extension part optional
)
- #1 is the whole thing
- #2 is the country number, can be empty
- #5 is the are code, can be empty
- #8 is the phone number only
- #9 is the first 3 digits
- #10 is the last 4 digits
- #11 is the whole extension, with text and number. Can be empty
- #12 is only the extension digits, can be empty
With those groups, it's easy to reformat the phone numbe the way we like them before persisting to a database.