liveBook · Manning

Non-greedy quantifier

As explained in Secrets of the JavaScript Ninja, Third Edition

A non-greedy operator is a regular-expression quantifier that initially matches as little text as possible while allowing the pattern to match.

Suppose a string contains two angle-bracketed fragments: <Ninjas><Unite!>. The pattern /<.*>/ matches the whole string because * is greedy. Change it to /<.*?>/ and it matches only <Ninjas>. Appending ? makes a repetition operator non-greedy: it consumes as little as needed for the rest of the pattern to match. section 12.2.2

“As little as needed” still depends on what follows the quantifier. In /[1-9][0-9]*\s+[a-z]+s/, the greedy [a-z]+ initially consumes all of dresses, then gives back its final s so the pattern can finish. A non-greedy [a-z]+? would instead stop before an earlier s that lets the pattern match. section 12.6.3

Use non-greedy matching when you want the first suitable stopping point, not the longest one. The angle-bracket example is deliberately not HTML: real HTML has edge cases better handled by a parsing library such as parse5. section 12.2.2

How Secrets of the JavaScript Ninja, Third Edition covers it

How deep it goes
Defines the ? suffix and demonstrates its effect, then contrasts greedy backtracking without tracing non-greedy execution in detail.
Examples
Contrasts /<.*>/ with /<.*?>/ on two angle-bracketed fragments and compares greedy and non-greedy letter matching.
What it assumes
Builds on basic regular-expression matching and repetition operators while defining non-greedy behavior directly.
What you can do after
Apply it via JavaScript regular expressions by appending ? to a repetition operator when the earliest suitable match is wanted.
How it connects
Connects repetition operators and regular-expression backtracking with the separate problem of HTML parsing.

Also explained in

Compare how 2 books explain non-greedy quantifier →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Secrets of the JavaScript Ninja, Third Edition. The section links point to the parts of the book it draws on.