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=deadbeefat 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.DEBUGin Python prints the compiled program —literal,in,max_repeat,branch— sore.compile(r"(\w+ )*", re.DEBUG)demystifies what your pattern actually compiled into.rg -Porpcre2greplet you A/B a pattern against gigabytes of real data without writing a harness.re.X/xverbose 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.25Twenty 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.
Java Pulled Primitive Patterns After Five Previews. JDK 28 Won't Compile Them.
Primitive types in patterns, instanceof, and switch previewed in every JDK from 23 to 27. On November 9 the Amber team withdrew the feature, and it won't be in JDK 28 even with --enable-preview. Here's why Valhalla changed the plan, what replaces it, and how to rewrite code that used it.
.NET 11 Is Out. Union Types Got the Applause, but unsafe Is What Changed.
.NET 11 shipped on November 10, 2026, and C# 15 finally has union types, the feature people have asked for since pattern matching arrived.
PHP 8.6 Finally Turns On the Session Settings You Were Told to Set in 2006
Every PHP hardening guide for two decades has told you to flip the same three session settings. PHP 8.6, due November 19, 2026, flips them for you: strict mode on, HttpOnly on, SameSite set to Lax.
Rust 1.100: The Never Type Is Finally Stable, and Cargo Learned to Wait
Rust 1.100 stabilizes the never type after ten years and five failed attempts, along with the core Allocator API and a DropGuard helper. The change most teams will notice is in Cargo: a one-line config that makes it skip any crate version published in the last few days.