Regex Greedy Quantifiers: What They Match, How They Differ from Lazy and Possessive, and When to Avoid Them
How greedy regex quantifiers work, why they overmatch, how lazy and possessive forms differ, and how to keep patterns portable across regex engines.
What greedy means in a regular expression
A quantifier sets how many times the preceding token may repeat. The basic quantifiers are *, +, ? and {n,m}. In nearly every regex flavor they are greedy by default: they take as many repetitions as they can, then give characters back one at a time only if the rest of the pattern would otherwise fail. Russian-language material calls these жадные квантификаторы. Two other modes change this behavior. Lazy quantifiers, also called reluctant or non-greedy, take as few repetitions as possible and expand only when needed. Possessive quantifiers take as many as possible and never give any back.
| Mode | Syntax | Starting behavior | Gives back characters? |
| Greedy | * + ? {n,m} | Takes as many as possible | Yes, through backtracking |
| Lazy | *? +? ?? {n,m}? | Takes as few as possible | Not applicable; it expands instead |
| Possessive | *+ ++ ?+ {n,m}+ | Takes as many as possible | No, never |
Is greedy matching right for your pattern?
Greedy is the right default when the repeated part should run all the way to a boundary that appears once, such as the end of a line, a run of digits, or trailing whitespace. Its main benefit is predictability: the match extends as far as it can. The tradeoff is overreach. If the closing delimiter appears more than once, a greedy quantifier runs past the first one and stops at the last one that still lets the pattern succeed. When the delimiter can repeat, use a lazy quantifier or a negated character class. When the input has nested or escaped structure, such as HTML, JSON or CSV with quoted fields, a real parser is more reliable than any quantifier.
What greediness actually changes
A regex does not alter text by itself. Greediness changes which span of the input the engine reports as the match. In a search, that span is what gets highlighted or extracted. In a replace operation, it is exactly the set of characters that gets rewritten. In the example below, the two patterns differ by one character, and they produce different results on the same input.
Input: say "hi" and "bye"
Greedy: ".*" matches "hi" and "bye"
Lazy: ".*?" matches "hi" (a second search finds "bye")
Negated: "[^"]*" matches "hi" (a second search finds "bye")
Here is how a backtracking engine handles the greedy version. The first quote matches the quote before hi. Then .* consumes everything to the end of the input. The final quote in the pattern now has nothing left to match, so the engine backtracks: .* gives up one character, which is the last quote in the input, and the pattern's closing quote matches it. The match covers both quoted words and the text between them. The lazy version starts with .*? matching nothing. It checks for a closing quote after each additional character and stops at the first one it finds.
Lazy does not mean shortest possible match
Regex engines try start positions from left to right, and the first position that produces any match wins. Greedy and lazy only decide how far a match extends from that start. Neither can move the start point. Readers who expect lazy quantifiers to find the shortest match anywhere in the input are often caught out by this.
Input: aab
Pattern: a.*?b
Result: aab (not ab, because a match starting at position 0 succeeds first)
A negated character class is often clearer than either
A pattern such as "[^"]*" describes the content directly: any characters except a quote. It cannot cross a closing quote, whether the quantifier is greedy or lazy, and it gives a backtracking engine fewer alternatives to try. Its main limitation is that it handles only single-character delimiters. Multi-character delimiters such as comment markers usually need a lazy quantifier or a lookahead.
Possessive quantifiers and atomic groups
A possessive quantifier such as .+ never returns characters it has consumed. For example, ".+" can never match, because .*+ also takes the closing quote and refuses to give it back. Possessive quantifiers are useful when giving characters back could never produce a valid match, as in \d++ followed by a non-digit. In that case they tell the engine to fail fast instead of retrying. An atomic group, written (?>...), applies the same no-backtracking rule to a whole subpattern.
Performance: when backtracking gets expensive
In a backtracking engine, a greedy quantifier that overshoots must retry shorter lengths. Usually this costs little. The risk comes from nested or overlapping quantifiers. A pattern like (a+)+$ applied to a long run of a characters followed by a character that breaks the match can make the engine try a number of ways to split the input that grows exponentially with input length. This is often called catastrophic backtracking. When attackers can control the input, it becomes a denial-of-service risk known as ReDoS. Common fixes are to remove the nested quantifier, replace . with a negated class, or use possessive quantifiers or atomic groups where the flavor supports them. Some engines, including Go's regexp package, Rust's regex crate and the NonBacktracking option in recent .NET versions, avoid backtracking entirely and guarantee time linear in the input length. They give up features such as backreferences in exchange. No benchmarks were supplied for this review, so no timing figures are given here.
Will the pattern behave the same after you copy it elsewhere?
Greedy quantifiers work the same way in every common flavor. Lazy and possessive syntax does not. A pattern that works in one regex tester can fail, throw an error, or silently mean something else in another engine. The table below summarizes commonly documented support. It reflects general documentation, was not tested for this article, and should be checked against the documentation for the exact version you use.
| Engine | Lazy quantifiers | Possessive quantifiers | Atomic groups |
| PCRE (PHP preg functions, grep -P) | Yes | Yes | Yes |
| Java | Yes | Yes | Yes |
| Python re | Yes | Python 3.11 and later | Python 3.11 and later |
| JavaScript | Yes | No | No |
| .NET | Yes | No | Yes |
| Ruby | Yes | Yes | Yes |
| Go regexp (RE2 syntax) | Yes | No | No |
| POSIX ERE (grep -E, sed -E) | No | No | No |
Watch for these other differences when copying patterns:
- POSIX engines use leftmost-longest matching for the whole expression, so results can differ from backtracking engines even without lazy syntax, particularly with alternation.
- In most flavors the dot does not match a newline by default. Whether a greedy .* crosses lines depends on a single-line or dotall flag, and the way that flag is enabled differs between engines.
- Patterns written inside ordinary string literals in languages like Java or C# need doubled backslashes. Pasting a tester's pattern into code without adjusting the escapes changes its meaning.
- Online regex testers usually let you choose a flavor. A match in one flavor does not prove the pattern works in another, so set the tester to the engine your code actually runs.
When a plain-text approach is better
- The delimiter is fixed and appears once: a literal find, split or index-of call is simpler and easier to read than .* around a delimiter.
- The input is structured data such as HTML, XML, JSON or quoted CSV: a parser handles nesting and escaping that quantifiers cannot.
- The pattern will run on untrusted input in a backtracking engine and cannot easily be made free of nested quantifiers: use a linear-time engine or a non-regex approach.
- Other people will maintain the code: a short explicit pattern, such as a negated class, is easier to review than one that depends on backtracking order.
Checklist before relying on a greedy pattern
- Test with input where the closing delimiter appears more than once.
- Test with input where the delimiter is missing, and confirm the pattern fails rather than matching too much.
- Check whether the dot needs to cross newlines, and set the flag explicitly.
- Look for nested quantifiers such as (x+)+ or (.) and rewrite them.
- Confirm that lazy or possessive syntax is supported by the target engine and version.
- In a replace operation, preview the matched spans before applying the change to stored text.
Gaps in this review
No tool-specific evidence, measurements or version details were supplied. The behavior described here follows widely documented regex semantics, and each example was checked by tracing the matching steps by hand rather than by running a particular engine. Engine support changes over time, as with Python's addition of possessive quantifiers in version 3.11. Before depending on lazy, possessive or atomic syntax, or on linear-time guarantees, confirm them in the documentation for your engine and version.