Skip to content

Lesson 4 of 13 · 18m

Writing a Pattern You Can Prove Works

A mechanical pipeline for shipping a regex: spec sentence first, corpus of positives/negatives/near-misses second, pattern last, timing asserted in CI.

The difference between a regex that ships and a regex that pages someone is rarely the pattern. It's the corpus it was tested against. A validator written by staring at the spec until the right squiggles come out will pass the three examples in the ticket and fail the fourth input real users send. The workflow that works is mechanical: spec, corpus, pattern, near-misses, timing.

1. Write the grammar before the pattern

Say what one unit of the data is, in a sentence, with its delimiters. Not "match a token" — "a token is 16 to 64 lowercase hex characters, preceded by token=, ended by &, whitespace, or end-of-line." Every clause of that sentence maps to a piece of the pattern:

lookbehind        body              lookahead
(?<=token=)       [0-9a-f]{16,64}   (?=&|\s|$)

If you can't write the sentence, the format wants a parser, not a pattern — that's the whole point of the when-not-to-regex lesson.

Notice what the sentence produced that staring at strings wouldn't: the delimiters became lookarounds, the character set became a bounded class, the length became {16,64}. Vague specs produce .*; precise specs produce patterns that can't overrun.

2. Build the corpus first

Three sets, in a file, before you touch the pattern:

  • Positives: real samples — paste them from logs, not from memory. token=9f8c2e1a4b3d7e0f, token=abc123&next=1, token=deadbeef at end of line.
  • Negatives: things that must not match: token=, token=XYZ, token=9f8z, mytoken=abc123.
  • Near-misses: inputs engineered to hurt the engine: token= followed by 10,000 hex characters, token=aaaa...aaa!. Near-misses are what ReDoS is made of.
import re, time

PAT = re.compile(r"(?<=token=)[0-9a-f]{16,64}(?=&|\s|$)")
cases = {
    "token=9f8c2e1a4b3d7e0f&next=1": "9f8c2e1a4b3d7e0f",
    "token=xyz&next=1":             None,
    "token=" + "a" * 10_000 + "!":  None,
}
for s, want in cases.items():
    t0 = time.perf_counter()
    m = PAT.search(s)
    ms = (time.perf_counter() - t0) * 1000
    got = m.group(0) if m else None
    assert got == want, (s[:40], got)
    print(f"{ms:7.2f} ms  {got}")

This file goes in the repo next to the code that owns the pattern. When someone edits the pattern, the corpus runs in CI, and the near-miss timings are the part reviewers should actually look at.

3. Debug with the engine's own eyes

  • regex101's regex debugger shows the step list the backtracker walks — bookmarks, backtracks, match length. When a pattern is slow, the debugger shows exactly which construct doubles.
  • re.DEBUG in Python prints the compiled program — literal, in, max_repeat, branch — so re.compile(r"(\w+ )*", re.DEBUG) demystifies what your pattern actually compiled into.
  • rg -P or pcre2grep let you A/B a pattern against gigabytes of real data without writing a harness.
  • re.X / x verbose mode lets you comment each clause of a big pattern in place — the closest thing regex has to a docstring.

4. Then fuzz the shape

hypothesis (Python) and fast-check (JS) generate inputs; property tests assert invariants like "output length <= input length" and "never throws, never exceeds N ms." Point the generator at near-miss territory — long runs of the repeated character, alternation overlaps — not random noise.

from hypothesis import given, strategies as st
import time

@given(st.text(alphabet="aA1! ", min_size=0, max_size=3000))
def test_never_hangs(s):
    t0 = time.perf_counter()
    PAT.search(s)
    assert time.perf_counter() - t0 < 0.25

Twenty seconds of fuzzing finds the backtracking shapes an afternoon of eyeballing misses.

Field notes

  • A pattern that only lives in a YAML file nobody can execute is a liability. Keep it in code where the test corpus can reach it.
  • Write the pattern for the reader first. (?<id>\d{4}-\d{2}) beats (\d{4}-\d{2}) the day someone adds a third group.
  • "It matches my example" is not the bar. The bar is: matches every positive, rejects every negative, and dies fast on every near-miss.

Keep reading

Related articles from the SudoSecurity blog.