Course contentsShow
← Python
Lesson 679 of 1,06011. Standard Library EssentialsFree lesson

Managing Greedy Versus Lazy Quantifiers in Regex Patterns

Control the behavior of regex quantifiers to ensure patterns match the intended text boundaries without consuming excessive input.

In this lesson, you will learn how to shift regex quantifiers from "greedy" to "lazy" mode to gain precise control over how much text your patterns consume.

By default, Python's regex quantifiers like *, +, and ? are greedy. This means they match as much text as possible—often more than you actually intend. When a regex engine encounters a greedy quantifier, it gobbles up the entire string and then "backtracks" only as much as necessary to satisfy the rest of the pattern.

Consider this string: text = "<div>Hello</div><div>World</div>"

If you use the pattern <div>.*</div>, the greedy .* will match everything from the first <div> to the very last </div> on the line. The result is one massive match: <div>Hello</div><div>World</div>. This happens because the .* tries to consume as much as it can while still allowing the final </div> to match.

To fix this, we turn the quantifier into a lazy (or non-greedy) quantifier by appending a ? symbol. Changing the pattern to <div>.*?</div> instructs the engine to match the smallest amount of text possible.

import re

text = "<div>Hello</div><div>World</div>"

# Greedy approach
greedy = re.findall(r"<div>.*</div>", text)
print(greedy) # ['<div>Hello</div><div>World</div>']

# Lazy approach
lazy = re.findall(r"<div>.*?</div>", text)
print(lazy)   # ['<div>Hello</div>', '<div>World</div>']

In the lazy version, .*? matches Hello and stops as soon as it sees the first closing </div>. It then resumes the process for the next part of the string, correctly isolating each tag pair.

Managing this behavior is vital when parsing nested structures or delimited content where you want to avoid "over-matching." By being explicit about whether you want the engine to grab the biggest possible chunk or the smallest, you ensure your regex patterns target the exact boundaries you need.

Key Takeaway: Greedy quantifiers match as much as possible, while appending a ? makes them lazy, forcing them to match as little as possible to satisfy the pattern.