December 5, 2026

Regex Greedy vs Lazy: Why .* Grabs Too Much, and When .*? Doesn’t Help

A tape measure pulled far past a small target mark on a workbench

The pattern <.*> was meant to match one HTML tag. Run against the line <b>bold</b> and <i>italic</i>, it matched the entire line, all 30 characters, as a single “tag.” Adding one question mark, <.*?>, turned that single oversized match into four correct ones. That one character is the difference between a greedy quantifier and a lazy one, and it’s behind a large share of regular expressions that work on the test string and fail on real data. The examples below were run in Python and with GNU grep and sed, and the outputs are copied from those runs.

Video: RobertElderSoftware on YouTube

Greedy is the default

What greedy means

Python’s re module documentation puts it plainly: the *, + and ? quantifiers “are all greedy; they match as much text as possible.” The documentation’s own example: if <.*> is matched against '<a> b <c>', “it will match the entire string, and not just '<a>'.”

Watching it happen

The test string <b>bold</b> and <i>italic</i> returned:

Pattern Matches
<.*> <b>bold</b> and <i>italic</i>
<.*?> <b>, </b>, <i>, </i>
<[^>]*> <b>, </b>, <i>, </i>

Why the greedy version overshoots

The .* first runs to the end of the line, because the dot matches anything. Then the engine needs a > to finish the pattern, finds none left, and backs up one character at a time until it finds the last > in the line. The match ends there, at the far end, because that’s the first place backing up succeeded.

A pair of scissors cutting a continuous strip of paper

Lazy quantifiers

Adding the question mark

The same documentation explains the fix: “Adding ? after the quantifier makes it perform the match in non-greedy or minimal fashion; as few characters as possible will be matched.” A lazy .*? starts by matching nothing, checks whether the rest of the pattern fits, and only then takes one more character. It stops at the first > it reaches.

The same idea, every quantifier

Every quantifier has a lazy form. In the tests:

Pattern Input Result
".*" say "hi" and "bye" "hi" and "bye"
".*?" say "hi" and "bye" "hi"
\d+ a123b 123
\d+? a123b 1, 2, 3
a{2,4} aaaaa aaaa
a{2,4}? aaaaa aa, aa

Lazy still has to finish the match

Lazy doesn’t mean shortest possible overall. re.match(r'a.*?b', 'axxbyyb') returned axxb, the shortest match starting at the first a. But the match must still start where the engine first succeeds, and the lazy part must still reach far enough for the rest of the pattern to fit. A lazy quantifier at the very end of a pattern, like x*? alone, happily matches nothing at all: the test returned an empty string from xxx.

Speed cuts both ways

Laziness also changes how much work the engine does. On a 200,000-character line with a short quoted word at the start, the greedy ".*" took about 0.17 milliseconds, running to the end and backing up, while the lazy ".*?" took about 0.002. Flip the input to one quote at each end of the same long line, and the lazy version became the slow one, about 1.5 milliseconds against 0.06, because it checked for a closing quote after every single character. The negated class "[^"]*" matched the greedy speed on that second test.

The better fix: say what’s allowed

Negated character classes

The third row of the first table, <[^>]*>, got the same four tags as the lazy version without being lazy at all. [^>] means “any character except >,” so the match can’t run past a closing bracket no matter how greedy it is. The quote example works the same way: "[^"]*" stops at the next quote.

Why it’s often preferable

A negated class states the real rule. “Everything up to the next quote” is a description of the data; “as little as possible” is a description of the engine’s search order. The negated version also works in tools that have no lazy quantifiers at all, which matters more than it seems.

Where a negated class falls short

It handles single-character delimiters. For a multi-character ending, such as matching up to --> at the end of an HTML comment, [^...] can’t express “not this three-character sequence,” and a lazy .*? followed by the delimiter is the practical choice.

Green computer code text scrolling on a dark screen

grep and sed don’t do lazy

The same pattern, different meaning

Run grep -oE '".*?"' on say "hi" and "bye" and the output is the whole greedy match, "hi" and "bye", exactly the same as without the question mark. GNU grep’s extended syntax has no lazy quantifiers. The GNU grep manual defines ? only as “The preceding item is optional and will be matched at most once.” Placed after .*, it’s read as making the already-optional .* optional again, which changes nothing.

Switching engines

The -P flag tells grep to “Interpret the pattern as a Perl regular expression,” per the manual, which also warns the option is “highly experimental” and may not be available everywhere. With grep -oP '".*?"', the output became "hi" and "bye" on separate lines, the lazy result. grep -oE '"[^"]*"' produced the same two lines without needing Perl syntax.

sed

GNU sed has no Perl mode at all: running sed -P stopped with “invalid option — ‘P’.” sed -E 's/".*"/X/' turned say "hi" and "bye" into say X, swallowing both quoted words. sed -E 's/"[^"]*"/X/' gave say X and "bye", replacing only the first. In sed, the negated class is the only way to get the narrow match.

Newlines and DOTALL

The dot stops at line breaks

Lazy matching often gets blamed for a different problem. Python’s documentation says that “In the default mode,” the dot “matches any character except a newline.” On the string <p>one\ntwo</p>, the pattern <p>.*?</p> found nothing, because the content spans a line break.

The flag that fixes it

Adding re.S, the DOTALL flag, which makes the dot “match any character at all, including a newline,” returned the full <p>one\ntwo</p>. The inline form (?s) does the same inside the pattern. A lazy pattern that mysteriously matches nothing on multi-line input is usually missing this flag rather than suffering from greediness.

When to stop using regex

Both the tag examples and this one hint at a limit. Regular expressions can pull simple tags out of a line, but nested HTML, attributes that contain > inside quotes, and comments break them quickly. For real HTML, an HTML parser is the right tool; regex is fine for logs, config files and simple text formats.

A green hedge maze with a building in background

Catastrophic backtracking

A pattern that takes exponentially long

Greedy and lazy describe the order in which an engine tries possibilities. They don’t limit how many it tries. OWASP’s page on regular expression denial of service lists (a+)+$ among its examples of “Evil Regex.” For an input like aaaaaaaaaaaaaaaaX, it says, “there are 65536 possible paths, and the number is double for each additional a.”

Timing it

Matching (a+)+$ against a run of as followed by !, which forces the match to fail, gave these times in Python:

Length of a-run (a+)+$ (a+?)+$ a+$
16 0.0024 s 0.0028 s 0.00003 s
18 0.0094 s 0.0127 s 0.00003 s
20 0.037 s 0.043 s 0.00001 s
22 0.149 s 0.172 s 0.00001 s
24 0.590 s 0.692 s 0.00001 s

Every two extra characters made the nested pattern about four times slower, doubling per character as OWASP describes. Making the inner quantifier lazy didn’t help at all; it was slightly slower. The simple a+$, which matches the same strings, stayed flat.

Possessive quantifiers and atomic groups

Python added a real fix in version 3.11, and not every language has one. Its documentation describes possessive quantifiers, written *+, ++ and ?+, as matching as much as possible but not allowing “back-tracking when the expression following it fails to match.” Atomic groups, (?>...), do the same for a whole group. In the test, (?>a+)+$ and (a++)+$ failed on the 25-character input in about a ten-thousandth of a second, against 0.59 seconds for the original. Not every engine has them

JavaScript, tested in Node.js, behaved like Python for greedy and lazy matching: /".*"/g returned "hi" and "bye" and /".*?"/g returned "hi" and "bye". It also supports the s flag, which matched <p>one\ntwo</p> across the line break. But it rejected both escape hatches. new RegExp("a++") threw “SyntaxError: Invalid regular expression: /a++/: Nothing to repeat,” and (?>a) threw “Invalid group.” In engines like that, the only defense is writing patterns that never nest quantifiers over the same text, or limiting how long an input can be before a regex ever sees it.

The rule of thumb

The lesson for any regex that runs on input from users is to avoid nested quantifiers over the same characters, and to reach for a possessive form when backtracking can’t possibly help.

Sources

  • re — Regular expression operations, Python documentation: https://docs.python.org/3/library/re.html
  • GNU Grep manual: https://www.gnu.org/software/grep/manual/grep.html
  • Regular expression Denial of Service (ReDoS), OWASP: https://community.owasp.org/attacks/Regular_expression_Denial_of_Service_-_ReDoS

920 Posts

Peter Kalafatis writes and edits X9M8. He holds a bachelor's degree from LIU Post and a master's in Media Studies from The New School, with academic work in the philosophy of science, human behavior, AI, and memetics.

View All Posts

Leave a Reply

Your email address will not be published. Required fields are marked *