Regular Expressions Greedy and Lazy quantifiers

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Parameters

QuantifiersDescription
?Match the preceding character or subexpression 0 or 1 times (preferably 1).
*Match the preceding character or subexpression 0 or more times (as many as possible).
+Match the preceding character or subexpression 1 or more times (as many as possible).
{n}Match the preceding character or subexpression exactly n times.
{min,}Match the preceding character or subexpression min or more times (as many as possible).
{0,max}Match the preceding character or subexpression max or fewer times (as close to max as possible).
{min,max}Match the preceding character or subexpression at least min times but no more than max times (as close to max as possible).
Lazy QuantifiersDescription
??Match the preceding character or subexpression 0 or 1 times (preferably 0).
*?Match the preceding character or subexpression 0 or more times (as few as possible).
+?Match the preceding character or subexpression 1 or more times (as few as possible).
{n}?Match the preceding character or subexpression exactly n times. No difference between greedy and lazy version.
{min,}?Match the preceding character or subexpression min or more times (as close to min as possible).
{0,max}?Match the preceding character or subexpression max or fewer times (as few as possible).
{min,max}?Match the preceding character or subexpression at least min times but no more than max times (as close to min as possible).

Remarks

Greediness

A greedy quantifier always attempts to repeat the sub-pattern as many times as possible before exploring shorter matches by backtracking.

Generally, a greedy pattern will match the longest possible string.

By default, all quantifiers are greedy.

Laziness

A lazy (also called non-greedy or reluctant) quantifier always attempts to repeat the sub-pattern as few times as possible, before exploring longer matches by expansion.

Generally, a lazy pattern will match the shortest possible string.

To make quantifiers lazy, just append ? to the existing quantifier, e.g. +?, {0,5}?.

Concept of greediness and laziness only exists in backtracking engines

The notion of greedy/lazy quantifier only exists in backtracking regex engines. In non-backtracking regex engines or POSIX-compliant regex engines, quantifiers only specify the upper bound and lower bound of the repetition, without specifying how to find the match -- those engines will always match the left-most longest string regardless.



Got any Regular Expressions Question?