TutreNews Learn

Groups, choices and lazy matching

Greedy and lazy matching

Goal: Predict what greedy quantifiers take and use ? to make them lazy · 9 min

By default quantifiers are greedy: they grab as many characters as possible and only give some back if the rest of the pattern needs them.

Take the HTML snippet <b>one</b> and <b>two</b>.

  • Greedy: <b>.*</b> matches from the first <b> to the last </b>: "<b>one</b> and <b>two</b>", one big match.
  • Lazy: <b>.*?</b> stops at the first possible </b>. Two matches: "<b>one</b>" and "<b>two</b>".

Adding ? after a quantifier makes it lazy (also called reluctant): *?, +?, ??, {n,m}?. It grabs as little as possible.

An alternative that is often faster and clearer is a negated class: <b>[^<]*</b> takes any characters except <, so it cannot run past the first closing tag.

Remember: for HTML in real projects use an HTML parser. Regular expressions are good for flat, predictable text, and brittle for nested structures.

Worked example: Quoted words

  1. Text: say "hi" and "bye".
  2. /".*"/ is greedy and returns the single long match from the first quote to the last quote.
  3. /".*?"/g returns the two quotes "hi" and "bye" separately.
const s = 'say "hi" and "bye"';
console.log(JSON.stringify(s.match(/".*"/g)));
console.log(JSON.stringify(s.match(/".*?"/g)));

Output:

["\"hi\" and \"bye\""]
["\"hi\"","\"bye\""]