Lesson 13 of 13 · 20m
Knowing When Not to Use Regex
The formats regex can't parse, the security bugs that come from trying, and a decision checklist for regex versus parser versus pipeline.
"Some people, when confronted with a problem, think 'I know, I'll use regular expressions.' Now they have two problems." Jamie Zawinski's 1997 line gets quoted as a joke, but there's an engineering fact under it: regular expressions recognize regular languages, and a lot of the data you're asked to process isn't one. Knowing where that boundary sits is the difference between a senior engineer's regex and a CVE.
Regex can't count nesting
A regular language can't track unbounded depth: balanced parentheses, nested HTML tags, JSON objects inside arrays inside objects, block comments inside block comments. PCRE's recursion ((?R), (?1)) technically escapes this, but then you've written a parser in the least maintainable language on the machine. If the format nests, use a parser.
Formats that already have parsers
| Data | Use this | Not this |
|---|---|---|
| HTML | DOMParser, BeautifulSoup, html5lib | <a href="(.*?)"> |
| JSON | JSON.parse, jq | "name":\s*"([^"]*)" |
| CSV | Python csv, Miller (mlr), qsv | split(",") |
| URLs | new URL(), urllib.parse | ^https?://([^/]+) |
| Email addresses | check for one @, then send a confirmation link | the 6 KB RFC 5322 regex |
The HTML row has its own lore: the most-upvoted answer in Stack Overflow history (2009, "Tony the Pony he comes...") is the one explaining you cannot parse HTML with regex — because HTML isn't regular, and the malformed markup real browsers accept defeats every pattern anyway.
CSV looks regular until it isn't
const row = '42,"Smith, Jane","say ""hi"" to Bob",2025-03-14';
console.log(row.split(",").length); // 5 — the quoted comma split a fieldEven the fix — a small quoted-field state machine — is incomplete: RFC 4180 allows raw newlines inside quoted fields, so "one record per line" is also false. That single fact kills every line-oriented CSV trick (grep, awk on NR, wc -l as a record count). Use a real CSV library, or mlr/qsv on the command line.
The email row in the table deserves the same skepticism. RFC 5322's grammar includes comments, quoted local parts, and domain literals — the famous "valid" regex runs kilobytes and still disagrees with real mailers. addr.count("@") == 1 plus a confirmation link is what production systems actually do.
The security version: URL allowlists
const allow = /^https:\/\/sudosecurity\.org/;
for (const t of ["https://sudosecurity.org.evil.test/", "https://sudosecurity.org@evil.test/"]) {
console.log(allow.test(t), new URL(t).hostname);
}
// true sudosecurity.org.evil.test true evil.test — both pass the regex, both land somewhere elseRegex-based redirect and SSRF allowlists are a recurring source of real vulnerabilities — host-prefix confusion and userinfo tricks (@) are the classics. Parse the URL, then compare hostname exactly against a set.
Where regex is the right call
- Tokenizing inside a real parser — each token type is a small anchored regex, and JS's sticky
yflag exists precisely for this. - Extracting fields from a log format you control or have documented.
- Validating narrow, flat formats:
^[a-z0-9-]{1,63}$for a slug,^[0-9a-f]{40}$for a git SHA. - One-off migrations and dead text: the throwaway
sedthat renames a field across 40,000 lines you'll never read again.
Field notes
- Ask in order: Is there a parser for this format? Does it nest? Is the input untrusted? Will someone else maintain this? Any "yes" pushes away from a clever regex.
- Every production regex deserves a table-driven test: matches, non-matches, near-misses.
- Prefer
URL,Intl,ipaddress,datetime. They encode decades of edge cases you won't remember. - The Zawinski quote is a joke about cleverness, not the tool.
[^,]+inside a parser is fine; a parser inside a regex is not.
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.