Editor

Normalize Phone Numbers

#332 · Regular expressions · Intermediate · 80 XP · about 16 min

People type phone numbers in many ways: 212-555-0187, (212) 555 0187, +1 212.555.0187. Write normalize_phone(text) that turns a North American phone number into the single format '(212) 555-0187', or returns 'invalid' when text is not a valid number.

A number is valid when, after removing every space, dash (-) and dot (.), what remains is made of these parts, in order, with nothing else:

  • an optional country code, written 1 or +1
  • a 3-digit area code, either bare or inside one pair of parentheses, like (212)
  • 7 more digits

The area code and the 7-digit part must not start with 0 or 1.

Examples

normalize_phone('212-555-0187')       # returns '(212) 555-0187'
normalize_phone('+1 (800) 555.0199')  # returns '(800) 555-0199'
normalize_phone('555-0187')           # returns 'invalid'
normalize_phone('112-555-0187')       # returns 'invalid'

The third number is too short, and the area code of the last one starts with 1.

Constraints

  • text has at most 50 characters, all ASCII.

Fastest solvers

Leaderboard

First solves only, ranked by stars and then time.