Greedy and stingy matching in RegExpr

Greedy matching means that a regular expression matches as many characters as possible. Regular expressions are greedy by default.

Stingy matching or minimal matching means a regular expression will match as few characters as possible. To use stingy matching, add a question mark ? to a quantifier.

Example

Given input "The fool is under the bar in the barn", try the following regular expressions:

Greedyfoo.*barThis will match "fool is under the bar in the bar".
Stingyfoo.*?bar  This will match "fool is under the bar".

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

Quantifiers with greedy and stingy variant

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

x*Zero or more x's (greedy, take as many as possible)
x*?Zero or more x's (stingy, take as few as possible)
x+One or more x's (greedy, take as many as possible)
x+?One or more x's (stingy, take 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 least m and at most n x's (greedy, take as many as possible)
x{m,n}?At least m and at most n x's (stingy, take as few as possible)
x{,n}At most n x's (greedy, take as many as possible)
x{,n}?At most n x's (stingy, take as few as possible)
x{n,}At least n x's (greedy, take as many as possible)
x{n,}?At least n x's (stingy, take as few as possible)

Regular expression syntax rules

©Aivosto Oy · RegExpr Help