Non-Greedy Quantifiers
By default, *, +, and ? are greedy — they match as much as possible. Add ? to make them non-greedy (lazy).
By default, *, +, and ? are greedy — they match as much as possible. Add ? to make them non-greedy (lazy).
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>"]
Non-greedy matching is essential when parsing HTML or nested structures.