R

TestRegex

← Back to Blog

Greedy vs Lazy Quantifiers: A Visual Guide

One of the most valuable concepts in regex is controlling "greediness". By default, standard quantifiers (*, +, {n,}) are greedy: they consume as much text as they possibly can while still allowing the pattern to match.

The Greedy Problem

Imagine parsing HTML (which, yes, you shouldn't do, but bear with me). Given <b>Bold</b> and <b>Brash</b>:

The pattern <b>.*</b> matches from the first opening tag to the last closing tag!

<b>Bold</b> and <b>Brash</b> // One giant match

The Lazy Solution

By appending a ? to the quantifier (.*?), you tell the engine to match as little as possible.

<b>.*?</b>

This yields two separate matches: <b>Bold</b> and <b>Brash</b>.