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.

PythonData Integrity

Code

pythonsnippet
19 lines
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+?: 2

Inside 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

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`.