Course contentsShow
← Java
Lesson 2293 of 2,87044. Regular ExpressionsFree lesson

Greedy vs Reluctant Quantifiers

Understand how greedy quantifiers match as much as possible while reluctant (lazy) versions use ? to match minimally.

Greedy vs Reluctant Quantifiers

You'll learn how quantifiers behave differently when matching patterns—either consuming as much text as possible or as little as needed.

The Core Idea

By default, quantifiers like *, +, ?, and {n,m} are greedy—they match as much of the input string as they can while still allowing the overall pattern to succeed. They're like a hungry person at a buffet, taking the maximum amount possible.

To make a quantifier reluctant (also called lazy), append a ? to it: *?, +?, ??, or {n,m}?. Reluctant quantifiers match the minimum amount necessary for the pattern to succeed. They're cautious, taking only what's absolutely needed.

How It Works

Consider matching HTML tags in the string "<div>content</div>" with the pattern <.*>:

Greedy (.*): Matches from the first < all the way to the last >, consuming "<div>content</div>" entirely—probably not what you wanted!

Reluctant (.*?): Matches from the first < to the nearest >, capturing just "<div>", then the pattern can match again to find "</div>".

Analogy

Think of a greedy quantifier as someone eating until the plate is empty, while a reluctant quantifier nibbles just enough to satisfy their hunger.

Example Scenario

When extracting text between quotes in "He said "hello" and "goodbye"":

  • Pattern ".*" (greedy) captures "hello" and "goodbye" as one match
  • Pattern ".*?" (reluctant) captures "hello" first, then "goodbye" separately

Key Takeaway: Greedy quantifiers (*, +, ?, {n,m}) maximize their match, while reluctant versions (*?, +?, ??, {n,m}?) minimize it—choose based on whether you want the longest or shortest possible match.