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

Practical — Phone Numbers, Dates, Emails (Pure Classes)

~12 min · practical, validation, composition

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

Composing primitives into real patterns

You now have enough tools to write surprisingly powerful patterns. Without knowing quantifiers *+? from Track 3, you can already do this with just {n} from earlier hints and the classes you've learned.

A US phone number

Shape: 3 digits, hyphen, 3 digits, hyphen, 4 digits. Pattern: \d{3}-\d{3}-\d{4}. Anchor with ^...$ for whole-string validation, leave bare for searching within text.

An ISO date

Shape: 4 digits, hyphen, 2 digits, hyphen, 2 digits. Pattern: \d{4}-\d{2}-\d{2}. Same composition principle.

Notice: this matches 9999-99-99. Regex validates SHAPE, not semantics. If you need to confirm the date is real, use a date library after the regex match.

A simple email (shape only)

Real email regex is famously cursed (the longest published one is over 6,000 characters). For 99% of cases, this is enough: [\w.+-]+@[\w-]+\.[\w.-]+

Read it left to right: word characters or .+- (local part), literal @, word characters or - (domain), literal dot, word characters or .- (TLD allowing subdomains).

The pattern this teaches

Real-world regex is built by:

  1. Describing the shape in English ("3 digits, hyphen, 3 digits, hyphen, 4 digits").
  2. Replacing each piece with the smallest character class or shorthand that fits (\d{3}, then - literal).
  3. Anchoring if you're validating, leaving open if you're searching.
  4. Testing with three inputs: a known-good, a known-bad, and an edge case.

You'll do this dozens of times in Tracks 6 and 7 with quantifiers + groups added. The mental motion is the same.

Code

Three real patterns from primitives·python
import re

# US phone (search anywhere in text)
phone = r'\d{3}-\d{3}-\d{4}'
re.findall(phone, 'Call 415-555-0199 or 212-867-5309')
# ['415-555-0199', '212-867-5309']

# ISO date validation (full string only)
date = r'^\d{4}-\d{2}-\d{2}$'
bool(re.fullmatch(date, '2026-05-04'))   # True
bool(re.fullmatch(date, '2026-5-4'))     # False (need 2 digits)
bool(re.fullmatch(date, '9999-99-99'))   # True (shape valid, semantics not)

# Email (loose, shape-only)
email = r'[\w.+-]+@[\w-]+\.[\w.-]+'
re.findall(email, 'reach me at hi+tag@example.co.kr today')
# ['hi+tag@example.co.kr']

External links

Exercise

Pick a data shape from your work today (a SKU number, an internal ID, a postal code, a license key). Write a pure-classes pattern that validates it. Use {n} for fixed counts. Test 3 known-good, 3 known-bad inputs.

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.