Quidquid latine dictum sit, altum sonatur. Quod erat demonstrandum.
RSS icon Email icon Home icon
  • sanitizing a phone number using a regular expression

    Posted on November 8th, 2007 Jordan No comments

    Expanding on the regular expression found in this blog post on validating phone numbers, I’ve found a regex that seems to match any U.S. phone number I can throw at it:

    ^[\(]?(\d{0,3})[\)]?[\s]?[\-]?(\d{3})[\s]?[\-]?(\d{4})[\s]?[a-zA-Z]*?[\.]?[\s]?(\d*)$


    Explanation of this regex:
    ^[\(]? string begins with optional open paren
    (\d{0,3}) 3 digit area code, captured
    [\)]? optional close paren
    [\s]? optional whitespace
    [\-]? optional dash
    (\d{3}) 3 digit exchange code, captured
    [\s]? optional whitespace
    [\-]? optional dash
    (\d{4}) 4 digit phone number, captured
    [\s]? optional whitespace
    [a-zA-Z]*? optional word (matches 'ext','extension','x', etc.)
    [\.]? optional period (matches the '.' in 'ext.')
    [\s]? optional whitespace
    (\d*)$ end of the string is the extension number, which can be any length