We are going to explain the concepts of greedy and lazy matching in regular expressions.
Greedy matching: The regular expression engine tries to match as much as possible.
Lazy matching (also called non-greedy or reluctant): The engine tries to match as little as possible.
We can demonstrate with an example. Let's use the string: "acd"
Suppose we want to extract the text between the tags and .
If we use a greedy pattern: <.*>
- The greedy
.* will match as much as possible, so it matches from the first '<' to the last '>',
which would be: "c"
But we want just the inner text "c". So we use a lazy pattern: <.*?>
- The lazy
.*? will match as little as possible, so it matches from the first '<' to the first '>',
which would be: "", and then if we do a global search, the next match would be "". But note:
if we are matching the entire pattern from the opening tag to the closing tag, we might use: <.?>.?<
However, the example we are going to use is: .*? for the entire tag content.
Actually, let's adjust: to get the content between the tags, we can use: (.*?) and then capture group 1.
But note: the original question is about greedy vs lazy on the quantifiers. So let's focus on the quantifier part.
In the pattern:
Greedy: .* -> matches as many characters as possible (until the end of the string or until the next part of the pattern fails)
Lazy: .*? -> matches as few characters as possible (until the next part of the pattern matches)
Example with the string "acd":
Pattern: <.*>
- This will match from the first '<' until the last '>' in the string, which is: "c"
Pattern: <.*?>
- This will match from the first '<' until the first '>' after that, which is: ""
But if we are trying to match the entire tag including content and closing tag, we might do: <.>.?
Actually, let's think of a pattern that matches the entire element: <[^>]>.?</[^>]*>
But that's not the point.
Let me show with a simpler example: the string "12345"
Pattern: \d+
Pattern: \d+?
- Lazy: matches "1" (the smallest possible match for \d+ is one digit, and then the engine will try to match the rest of the pattern, but if there is no more pattern, then it returns the first digit)
However, note that in many regex engines, if the pattern is just \d+? and we are looking for a match, it will still match as many as needed to satisfy the entire pattern. But since there is no more pattern, it will match one digit and then stop because the engine doesn't need to match more.
But when combined with other patterns, the difference becomes clear.
Example:
String: "a123b"
Pattern: a\d+b
Greedy: matches "a123b"
If we make the quantifier lazy: a\d+?b
- It will match "a1" and then try to match 'b'? Actually, it will match:
a -> matches 'a'
\d+? -> matches as few as possible, so it matches '1' (one digit) and then tries to match 'b'. The next character is '2', so it fails. Then it backtracks and lets \d+? match another digit (so now it matches '12') and then tries 'b'? Still fails (next is '3'). Then matches '123' and then tries 'b'? Now the next is 'b', so it matches. So it matches "a123b".
But wait, that's the same as greedy? Actually, in this case, because the pattern requires a 'b' at the end, the lazy quantifier will still match until it finds a 'b'. So it matches the same.
Let's try with a string that has multiple possibilities: "a123b456b"
Pattern: a\d+b
Greedy: matches from the first 'a' to the last 'b', so "a123b456b"
Pattern: a\d+?b
Lazy: matches from the first 'a' to the first 'b', so "a123b"
So the lazy version stops at the first opportunity to satisfy the entire pattern.
Let's use the example from the original question with tags:
String: "c"
Pattern: <.>
Greedy: matches the whole string because . is greedy and matches until the last '>', which is the one in the closing tag.
Pattern: <.*?>
Lazy: matches only the opening tag: ""
But if we want to match the entire element (from opening tag to closing tag) and we use:
Pattern: <.>.?</.*> ... that's not correct.
Actually, to match the entire element with content, we can do: <[^>]>.?</[^>]*>
But let's break it down.
However, the key point is that the quantifier's greediness changes how much it consumes.
In summary:
Greedy quantifiers:
* , + , ? , {min,} , {min,max} (by default they are greedy)
They try to match as much as possible, and then if the rest of the pattern fails, they backtrack and give up characters one by one until the pattern succeeds or they run out.
Lazy quantifiers:
*? , +? , ?? , {min,}? , {min,max}?
They try to match as little as possible, and then if the rest of the pattern fails, they will take more characters (one by one) until the pattern succeeds or they run out.
Let me illustrate with a simple example in code (using Python regex, but the concept is the same in most regex engines):
import re
s = "a123b456b"
greedy = re.findall(r'a\d+b', s) # ['a123b456b']
lazy = re.findall(r'a\d+?b', s) # ['a123b']
But note: if we use the pattern without the global flag, the first match for greedy is the entire string, and for lazy it's the first occurrence.
Another example with a single match:
s = "a123b"
greedy: a\d+b -> matches the whole "a123b"
lazy: a\d+?b -> also matches the whole "a123b", because the lazy quantifier matches one digit, then tries to match 'b' (fails), then another digit (fails), until it matches all three and then the 'b' succeeds.
So the difference is more evident when there are multiple possible ways to satisfy the pattern.
Let me try with: s = "a1b2b"
Pattern: a\d+b
Greedy: matches from the first 'a' to the last 'b': "a1b2b"
Pattern: a\d+?b
Lazy: matches from the first 'a' to the first 'b': "a1b"
So the lazy version stops at the first 'b' that makes the pattern complete.
In the context of the original tag example:
String: "c"
Pattern: <.>
Greedy: matches from the first '<' to the last '>', which is the entire string: "c"
Pattern: <.?>
Lazy: matches from the first '<' to the first '>', which is ""
But note: if we want to match the entire tag including the content and the closing tag, we might use: <.>.?< ... that's not a good pattern.
Alternatively, we can use: <[^>]>.?</[^>]*>
But that's a different pattern.
The key takeaway:
Greedy: match as much as you can, then backtrack if needed.
Lazy: match as little as you can, then expand if needed.
I hope that clarifies.
Greedy vs. Lazy Matching in Regular Expressions
In regex, quantifiers (like *, +, ?, {}) control how many characters a pattern matches. Their default behavior is greedy, but you can make them lazy (also called non-greedy or reluctant) by adding a ? after the quantifier.
1. Greedy Matching (Default)
- Goal: Match as many characters as possible while still allowing the overall regex to succeed.
- How it works: The engine starts by matching the maximum allowed characters, then backtracks (reduces the match) if the rest of the pattern fails.
Example:
Regex: a.+b on string "a123b456b"
- Greedy
.+ first tries to match "123b456" (as many as possible).
- The final
b then fails (no b after 456).
- Backtrack:
.+ gives up one character at a time until b matches → final match: "a123b456b" (longest possible).
Common greedy quantifiers:
* → matches 0 or more (as many as possible)
+ → matches 1 or more
? → matches 0 or 1 (but tries 1 first)
{m,n} → matches between m and n (tries n first)
2. Lazy Matching (Non-Greedy)
- Goal: Match as few characters as possible while still allowing the overall regex to succeed.
- How it works: The engine starts with the minimum allowed characters, then expands the match if the rest of the pattern fails.
Example:
Regex: a.+?b on "a123b456b"
- Lazy
.+? first matches "1" (minimum 1 character).
- The final
b fails (next char is 2).
- Expand:
.+? adds one character at a time until b matches → first match: "a123b" (shortest possible).
- If searching globally, next match:
"a456b".
Lazy versions:
*? → matches 0 or more (as few as possible)
+? → matches 1 or more (as few as possible)
?? → matches 0 or 1 (prefers 0)
{m,n}? → matches between m and n (prefers m)
Key Comparison Table
| Aspect | Greedy (.*, .+) | Lazy (.*?, .+?) |
|---|
| Goal | Maximal match | Minimal match |
| Start | Tries longest first | Tries shortest first |
| Backtracking | Reduces match (if needed) | Expands match (if needed) |
| Use Case | When you want broad capture | When you want narrow capture |
| Example | <.*> → matches whole tag | <.*?> → matches only <b> |
Practical Example: HTML Tags
String: <div>Hello</div> <div>World</div>
When to Use Which?
- Greedy: When you want to capture everything up to the last possible delimiter (e.g., between the last occurrence of two patterns).
- Lazy: When you want to capture up to the first occurrence of a delimiter (e.g., between the first opening and closing tags).
Important Notes
- Greedy isn’t always “maximal” — it matches as much as possible while still letting the entire regex succeed. If the regex fails, it backtracks.
- Lazy isn’t always “minimal” — it matches as little as possible while still letting the entire regex succeed. If the regex fails, it expands.
- Performance: Lazy quantifiers can be slower in some cases because they may require more backtracking steps (but not always).
Quick Test
Regex: ".+" on "abc"def"
- Greedy:
"abc" (matches until the last ").
- Lazy:
"a" (matches until the first ").
Summary:
- Greedy = “Take as much as you can, then give back if needed.”
- Lazy = “Take as little as you can, then take more if needed.”
Use ? after a quantifier to switch from greedy to lazy behavior.