Skip to content

Instantly share code, notes, and snippets.

@marcaube
Last active August 29, 2015 13:56
Show Gist options
  • Save marcaube/9263100 to your computer and use it in GitHub Desktop.
Save marcaube/9263100 to your computer and use it in GitHub Desktop.

US/CAN phone regex

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

The regex

((\d{1})?([\s-])?(\()?(\d{3})?(\))?([\s-])?((\d{3})[\s-](\d{4}))(\s.+?\s?(\d{1,5}))?)

See it in action

The regex explained

(
    (\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
)

The interesting capture groups

  • #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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment