Normalize phone numbers
A regex exercise from Regexdrill. Solve it with a pattern box with live highlighting in your browser, checked against hidden test strings, and it is checked the moment you submit.
The task
Each line is one ten-digit US phone number in one of these shapes: (555) 123-4567, 555-123-4567, 555.123.4567, 555 123 4567 or 5551234567. Rewrite every line as 555-123-4567: three digits, a hyphen, three digits, a hyphen and four digits.
What this exercise teaches
\(?(\d{3})\)?[ .-]?(\d{3})[ .-]?(\d{4}) with the replacement $1-$2-$3 captures the digits whatever sits between them. Deleting every non-digit would also remove the hyphens the output needs.
A hint if you get stuck
Capture the three digit groups and make the parentheses and the separator between groups optional. Write the hyphens in the replacement.
Try it now, free, no account needed
Every exercise on Regexdrill is free to try. Open it on the practice page, solve it, and get instant feedback with a hint. A free account adds the worked solution; Pro adds timed mode and the certificate.
Open this exerciseMore exercises in Extraction and cleanup
- Log lines: level and messageFree
- key=value pairsFree
- The third CSV fieldFree
- HashtagsFree
- Host names from URLsFree
- Trim whitespaceFree
- Collapse repeated spacesFree
- Reformat MM/DD/YYYY as YYYY-MM-DDFree
- Swap Last, First to First LastFree
- Strip HTML tagsFree
- Keep only the digitsFree
- CSV fields with quotesFree
- Link text inside <a> tagsFree
- Web server access logFree