Regular Expression - Greedy Quantifier

> Procedural Languages > Multilingual Regular Expression Syntax (Pattern)

1 - About

Greedy quantifier

A Greedy quantifier will match the longest possible string whereas Lazy quantifier will match the shortest possible string. Match as few as possible, repeat as few times as possible.

Advertising

3 - List

Quantifier
* Matches 0 or more occurrences
of the preceding element. See Regexp - Star
ab*c matches ac, abc, abbc, abbbc, and so on
+ Matches 1 or more occurrences
of the preceding element
ab+c matches abc, abbc, abbbc, and so on, but not ac
? Matches 0 or 1 occurrence
of the preceding element
colou?r matches both color and colour
{ start min/max quantifier
} end min/max quantifier
{m} Matches exactly m times
{m,} Matches at least m times
{m,n} Matches at least m times but no more than n times

4 - Example

4.1 - Hello World

For example in the termhello

  • the greedy h.+l matches hell
  • but the lazy h.+?l matches hel.
Advertising

4.2 - HTML

<em>Hello World</em>
  • The greedy pattern <.+> will match <em>Hello World</em>
  • The lazy pattern <.+?> will match <em> and </em>