Parsing and Formatting Phone Numbers with Regex

Using regular expressions to parse and format phone numbers from various input styles

Python
import re

def parse_phone_number(phone):
    # Remove all non-digit characters
    digits = re.sub(r'\D', '', phone)
    
    # Check if it's a valid 10-digit number
    if len(digits) == 10:
        return digits
    # Check if it's a valid 11-digit number starting with 1 (US country code)
    elif len(digits) == 11 and digits.startswith('1'):
        return digits[1:]
    else:
        return None

def format_phone_number(digits):
    if not digits or len(digits) != 10:
        return "Invalid number"
    return f"({digits[:3]}) {digits[3:6]}-{digits[6:]}"

phone_numbers = [
    "123-456-7890",
    "(987) 654-3210",
    "1234567890",
    "+1 (800) 555-1234",
    "12345",
    "123 456 7890",
    "1-800-123-4567"
]

for phone in phone_numbers:
    parsed = parse_phone_number(phone)
    if parsed:
        formatted = format_phone_number(parsed)
        print(f"Original: {phone}")
        print(f"Formatted: {formatted}")
    else:
        print(f"Original: {phone}")
        print("Invalid phone number")
    print("---")
Click Run or press shift + ENTER to run code.