Greedy Versus Lazy Quantifier Spans
Greedy quantifiers stretch to the longest span and lazy quantifiers, written with an extra ?, stop at the shortest span that still succeeds.
Code
import re
# Greedy quantifiers match the LONGEST span that can still succeed;
# adding ? makes the quantifier lazy: the SHORTEST span that succeeds
markup = '<p>alpha</p><p>beta</p>'
greedy = re.search(r'<p>(.*)</p>', markup)
print('greedy :', repr(greedy.group(1)))
lazy = re.search(r'<p>(.*?)</p>', markup)
print('lazy :', repr(lazy.group(1)))
# finditer with lazy quantifiers walks one <p> element per match
for m in re.finditer(r'<p>(.*?)</p>', markup):
print('element :', m.group(1))
# The same switch works on + : \d+ takes the whole run, \d+? takes one
print('digits+ :', re.match(r'\d+', '2026').group(0))
print('digits+?:', re.match(r'\d+?', '2026').group(0))Output
Captured from a sandboxed run of this snippet in the build pipeline.
greedy : 'alpha</p><p>beta'
lazy : 'alpha'
element : alpha
element : beta
digits+ : 2026
digits+?: 2Inside the snippet
A single loop drives the file — for m in re.finditer(r'<p>(.*?)</p>', markup).
Demo state sits in top-level bindings: markup, greedy, lazy.
What to watch for
- It carries its own context — no imports beyond the runtime’s own surface.
Putting it to use
Each step the file takes is announced in the output: greedy :, lazy :, element :.
The core lines, annotated
for m in re.finditer(r'<p>(.*?)</p>', markup):
print('element :', m.group(1))
Interactive Tools for This Topic
Regular Expression TesterTest regular expressions against sample text with live match highlighting, capture group extraction, and flags support for global, case-insensitive, and multiline modes.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Nginx Location Block TesterTest any URL path against Nginx location blocks using authentic Nginx precedence (= exact, ^~ prefix, regex ~ and ~*, and longest prefix) with trace output.Regex Backreference ExplainerScan a regular expression to list its capturing groups, named groups, non-capturing groups, and backreferences, with warnings for dangling references.
FAQ
- Are there dependencies to manage?
- No. There are no dependencies to declare or install. Every import resolves inside the standard library — `re`. Its state lives in module-level bindings: `markup`, `greedy`, `lazy`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.