Skip to content

Lesson 2 of 13 · 20m

Quantifiers, Classes, and Anchors: Saying Exactly What You Mean

Greedy, lazy, and possessive quantifiers, why negated classes beat lazy dots, and the anchors that turn 'contains' into 'is'.

.* is the regex equivalent of "I couldn't be bothered to describe this." I once reviewed a log-redaction rule, token=.*, that had been deleting everything after the token on every line for six months — values, flags, the request ID you would have wanted during the incident. Nobody noticed because the lines still looked redacted. The fix was token=[^&\s]+: say what a token is, not what it ends before. Most broken regexes aren't wrong; they're vague — and vagueness is where both the bugs and the slowness come from.

Greedy, lazy, possessive

Every repetition operator — *, +, ?, {n,m} — comes in up to three modes:

  • Greedy (.*, \d+): take as much as possible, give characters back on failure. The default everywhere.
  • Lazy (.*?, \d+?): take as little as possible, extend on failure.
  • Possessive (.*+, \d++) and atomic groups ((?>...)): take as much as possible and never give it back. PCRE2, Java, and Python 3.11+ support them; JavaScript does not — V8 has no possessive quantifiers and the u flag doesn't change that.

Lazy is not a correctness fix and not a performance fix. It only changes which match the search finds first — "(.*?)" on "a" "b" still has to consider every closing quote; it just considers them nearest-first. Possessive quantifiers and atomic groups are a performance tool: they delete bookmarks, so a doomed match fails after one pass instead of retrying every split point.

Negated classes beat lazy dots

const url = "/checkout?session=9f8c2e1a&step=payment&retry=1#card";
console.log(url.match(/session=(.*)&/)[1]);    // 9f8c2e1a&step=payment — greedy eats to the last &
console.log(url.match(/session=([^&#]*)/)[1]); // 9f8c2e1a — a value is exactly "not & or #"

[^&#]* encodes the grammar instead of the engine's mood: a query value runs until & or #. It is correct on every input, and the engine can't backtrack into it in any interesting way.

The same rule repairs the redaction regex: token=[^&\s]+ describes a token as "non-delimiter characters" and can never overrun the field. Every .* and .*? in a codebase is a TODO asking what the text actually is.

{n,m} is documentation that executes

\d{1,3} on an octet and [0-9a-f]{16,64} on a token do double duty: they reject nonsense inputs and they bound the engine's work before it starts. An unbounded + on an endpoint that accepts form posts is an open invitation — not because + is evil, but because "any number of characters" is never what the field means.

Anchors turn "contains" into "is"

const zip = /\d{5}/;
console.log(zip.test("90210"));                        // true
console.log(zip.test("UPS 1Z999AA10123456784"));       // true — five digits somewhere
const strictZip = /^\d{5}(?:-\d{4})?$/;
console.log(strictZip.test("90210-1234"));             // true
console.log(strictZip.test("UPS 1Z999AA10123456784")); // false

An unanchored validation regex is a "contains" check — the single most common regex bug in code review. \b is the other anchor with real semantics: a zero-width boundary between a word character and a non-word character, so \bERROR\b matches ERROR: but not TERRORIST. And in Python, ^/$ aren't the whole story — $ matches before a trailing newline. The flags lesson covers re.fullmatch and \Z; the point here is that an anchor's job is turning "appears somewhere" into "is exactly this."

Classes worth having in muscle memory

[^"]          anything but a quote — including newlines; if the value can't span lines, write [^"\n]
[ \t]         horizontal whitespace only; \s also eats \n and \r
[\w.-]        hyphen last so it's literal; dot is literal inside a class
[[:digit:]]   POSIX class, works in grep/sed/awk where \d doesn't exist
\d{1,3}       bounded repetition: cheaper and more honest than \d+

Field notes

  • [A-z] is a bug: between Z and a in ASCII sit [, \, ], ^, _, and the backtick. Write [A-Za-z].
  • \s+ run across a whole buffer swallows newlines and glues records together. When you mean "spaces on this line," write [ \t]+.
  • In Python, x{,5} means 0 to 5; in JavaScript without u it is the literal text {,5}. Write {0,5}.
  • Bound everything you can. \d{1,10} documents intent and caps the work; \d+ invites a megabyte of digits on an endpoint that takes form posts.

Keep reading

Related articles from the SudoSecurity blog.