Greedy and stingy matching in RegExpr

Back to help contents

Usually, regular expressions are greedy: they match as much of the input as possible. However, you can add the suffix "?" to any quantifier to use stingy, or minimal matching. This means that as few characters as possible will be matched.

Example: Given text "The food is under the bar in the barn", try the following regular expressions:

Greedy:"foo.*bar"This will match "food is under the bar in the bar"
Stingy:"foo.*?bar"This will match "food is under the bar"

As you can see, .* matched as much as possible, where .*? matched only as much as was needed.

The following table lists the quantifiers that have a greedy and a stingy variant.

x*Zero or more x's (greedy, takes as many as possible)
x*?Zero or more x's (stingy, takes as few as possible)
x+One or more x's (greedy, takes as many as possible)
x+?One or more x's (stingy, takes as few as possible)
x?One or zero x (greedy, try one first)
x??Zero or one x (stingy, try zero first)
x{m,n}At most n and at least m x's (greedy, takes as many as possible)
x{m,n}?At least m and at most n x's (stingy, takes as few as possible)
x{n,}At least n x's (greedy, takes as many as possible)
x{n,}?At least n x's (stingy, takes as few as possible)

Regular expression syntax rules

©Aivosto Oy