Greedy vs. Non-Greedy Regex Quantifiers: How One Character Changes Matches
Regex quantifiers like * and + are greedy by default, meaning they match as much input as possible before backtracking to satisfy the rest of the pattern. Adding a ? after a quantifier makes it non-greedy, causing it to match as little as possible instead. In a real-world example involving WP-CLI JSON output mixed with PHP deprecation warnings, a non-greedy pattern incorrectly truncated nested JSON by stopping at the first closing brace, while the greedy version correctly captured the full payload. However, when the surrounding pattern is strict enough to allow only one valid match position, greedy and non-greedy quantifiers produce identical results. The practical takeaway is that choosing between greedy and non-greedy matters most when the rest of the pattern is loose, not when it uniquely pins down a position in the input.
This is an AI-generated summary. ShortSingh links to the original source for the complete article.
Discussion (0)
Log in to join the discussion and vote.
Log in