C.W.K.
Stream
Lesson 10 of 12 · published

Phone Numbers

~8 min · phone, validation, international

Level 0Pattern-Curious
0 XP0/90 lessons0/15 achievements
0/100 XP to next level100 XP to go0% complete

Phone numbers are wildly variable

US: (415) 555-0199, 415-555-0199, 415.555.0199, +1 415 555 0199. Korea: 010-1234-5678, 02-1234-5678. UK: +44 7700 900123. Every country has variants.

The shape-loose pattern

For finding phone-like things in text:

\+?\d[\d\s().-]{7,}\d

Optional plus, digit, then 7+ characters of digits/spaces/parens/dots/dashes, ending in a digit.

US-specific validation

^(?:\+1\s*)?(?:\(\d{3}\)|\d{3})[\s.-]?\d{3}[\s.-]?\d{4}$

Optional +1, area code (parens or bare), separator, exchange, separator, line number.

For real validation: libphonenumber

Google's libphonenumber handles every country, format variant, and validation rule. Bindings exist for Python (phonenumbers), JS, Java, etc. If your app accepts international phone numbers, use it. Regex won't get you there.

The simplest pattern that's useful

If you just want "contains 10+ digits in a phone-shaped layout," the loose pattern above is fine for free-form text extraction. Validation requires either country-specific patterns OR libphonenumber.

Code

Phone patterns·python
import re

# Loose extraction
PHONE_LOOSE = re.compile(r'\+?\d[\d\s().-]{7,}\d')
re.findall(PHONE_LOOSE, 'call (415) 555-0199 or +82 10-1234-5678')
# ['(415) 555-0199', '+82 10-1234-5678']

# US-specific
US_PHONE = re.compile(
    r'^(?:\+1\s*)?(?:\(\d{3}\)|\d{3})[\s.-]?\d{3}[\s.-]?\d{4}$'
)
bool(US_PHONE.fullmatch('(415) 555-0199'))  # True
bool(US_PHONE.fullmatch('415-555-0199'))    # True
bool(US_PHONE.fullmatch('+1 415 555 0199')) # True
bool(US_PHONE.fullmatch('415-555'))         # False (incomplete)

# For real validation
# pip install phonenumbers
# import phonenumbers
# phone = phonenumbers.parse('+82 10-1234-5678', None)
# phonenumbers.is_valid_number(phone)  # True
# phonenumbers.format_number(phone, phonenumbers.PhoneNumberFormat.E164)
# # '+821012345678'

External links

Exercise

Install phonenumbers. Take 5 phone numbers from your contacts (in different formats) and validate each with libphonenumber. Try the same with your regex. Note where regex fails and libphonenumber succeeds.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.