Skip to content

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

DataUse thisNot this
HTMLDOMParser, BeautifulSoup, html5lib<a href="(.*?)">
JSONJSON.parse, jq"name":\s*"([^"]*)"
CSVPython csv, Miller (mlr), qsvsplit(",")
URLsnew URL(), urllib.parse^https?://([^/]+)
Email addressescheck for one @, then send a confirmation linkthe 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 field

Even 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 else

Regex-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 y flag 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 sed that 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.