Greedy vs. Lazy
When to use .* or .*? in your regex:
- Greedy:
.*(Matches as much as possible) - Lazy:
.*?(Matches as little as possible)
Example:
import re
# Greedy
pattern = re.compile(r'\d+')
s = '123456'
match = pattern.match(s)
if match:
print(match.group())
# Lazy
pattern = re.compile(r'\d+')
s = '123456'
match = pattern.search(s)
if match:
print(match.group())
More info: More Greedy than Lazy