SyntaxStudy
Sign Up
Python Non-Greedy Quantifiers
Python Intermediate 4 min read

Non-Greedy Quantifiers

Non-Greedy Quantifiers

By default, *, +, and ? are greedy — they match as much as possible. Add ? to make them non-greedy (lazy).

Example
import re

html = "<p>First</p><p>Second</p>"
greedy    = re.findall(r"<p>.*</p>",  html)
non_greedy = re.findall(r"<p>.*?</p>", html)

print(greedy)     # ["<p>First</p><p>Second</p>"]
print(non_greedy) # ["<p>First</p>", "<p>Second</p>"]
Pro Tip

Non-greedy matching is essential when parsing HTML or nested structures.