Greedy versus lazy quantifiers

Back to list2026-07-18
You

My pattern swallows the whole line.

ChatGPT

.* is greedy: it takes everything, then backtracks. Use .*? for the shortest match, or better, a negated class like [^"]* which cannot cross the delimiter at all and does not backtrack.

You
backup-topology.png
You

A pattern hangs on certain inputs.

ChatGPT

Catastrophic backtracking, usually from nested quantifiers like (a+)+. Rewrite so each position has one way to match, or use a library with a linear-time engine. Input length alone rarely causes it; ambiguity does.