Skip to content

Lesson 7 of 9 · 24m

Validation and Extraction Patterns That Survive Production Data

Design validators and extractors for real operational text — strict where the contract is strict, tolerant where humans write, and explicit about partial matches.

Regex earns its keep in the middle ground: too structured for simple string operations, too irregular for a full grammar. Invoice numbers, log fields, semantic versions, identifiers, slugs, and small machine formats are good territory. Email addresses and URLs are warning examples: everyone thinks they are simple until production data arrives.

Validation and extraction are different jobs

Validation asks whether the whole value is in the expected language. Extraction asks where inside larger text the useful piece occurs:

INVOICE = re.compile(r"INV-(?P<year>\d{4})-(?P<num>\d{5})")

if not INVOICE.fullmatch(candidate):
    raise ValueError("invalid invoice number")

for m in INVOICE.finditer(log_text):
    print(m.group("year"), m.group("num"))

fullmatch supplies strictness for validation. finditer intentionally searches during extraction. The same local shape can serve both jobs because the anchoring decision lives at the call site.

Strict machine formats deserve strict regexes

A good validator encodes length, alphabet, delimiters, and numeric ranges explicitly. Semantic versioning is the classic trap: casual \d+\.\d+\.\d+ accepts leading zeroes semver forbids and rejects valid prerelease or build metadata. If the format has a specification, read it before writing the regex.

Human input deserves explicit policy

Slugs and usernames are product policy rather than universal truth:

SLUG = re.compile(r"[a-z0-9](?:[a-z0-9-]{0,38}[a-z0-9])?")

This says lowercase ASCII alphanumeric edges, hyphen inside, maximum forty characters. It is not "the correct slug regex"; it is a clear policy. Put policy in constants, tests, and documentation.

Extraction needs termination rules

When pulling fields from logs, define what ends the field:

LOG = re.compile(
    r"^(?P<ts>\S+)Z level=(?P<level>[A-Z]+) "
    r"user=(?P<user>[^\s]+) msg=(?P<msg>.*)$"
)

[^\s]+ works for user only because the format says users cannot contain whitespace. If quoted strings or escaped spaces appear, this regex is no longer sufficient. That is evidence the format is a grammar.

Test with a corpus, not a handful of examples

Build fixtures from real data, redacted where necessary. Include valid edge cases, near-misses, malformed delimiters, empty fields, maximum lengths, and upstream format drift. Add a fixture whenever production parsing fails. Regexes rot silently when producers change shape.

Field notes

  • fullmatch is the default for validators; search and finditer are for extraction.
  • A good field pattern names the terminating delimiter as carefully as the field alphabet.
  • Real specifications beat convenient patterns.
  • Keep production-derived fixtures in tests, especially failures caused by upstream drift.
  • Do not regex-validate JSON, CSV, XML, HTML, URLs, dates, or phone numbers when a real parser exists.

Was this lesson helpful?

Sign in to rate