Minimal or non-greedy quantifiers

Regular expressions are generally considered greedy because an expression with repetitions will attempt to match as many characters as possible. The asterisk (*), plus (+), question mark (?), and curly braces ({}) metacharacters exhibit 'repetitious' behavior, and attempt to match as many instances as possible.

To make a subexpression match as few characters as possible, a question mark (?) can be appended to these metacharacters to make them minimal or non-greedy. The following table describes the non-greedy quantifiers.

Table 1. Minimal/non-greedy quantifiers
Quantifier Description Examples
*? Matches zero or more instances of the preceding atom. Matches as few instances as possible. Given an input string of Netcool Tool Library:
  • The first group in ^(.*l).*$ matches Netcool Tool .
  • The first group in ^(.*?l).*$ matches Netcool.
+? Matches one or more instances of the preceding atom. Matches as few instances as possible. Given an input string of little:
  • .*?l matches l.
  • ^.+l matches littl.
?? Matches zero or one instance of the preceding atom. Matches as few instances as possible. .??b matches ab in abc, and b in bbb.

.?b matches ab in abc, and bb in bbb.

{m , n} ? Matches from m to n instances of the preceding atom, where m is the minimum and n is the maximum. Matches as few instances as possible.
Note: m and n are unsigned decimal integers between 0 and 255.
Given an input string of Netcool Tool Cool Fool Library:
  • ^((.*?ool)*).*$ matches Netcool Tool Cool Fool.
  • ^((.*?ool)+).*$ matches Netcool Tool Cool Fool.
  • ^((.*?ool)+?).*$ matches Netcool.
  • ^((.*?ool){2,5}).*$ matches Netcool Tool Cool Fool.
  • ^((.*?ool){2,5}?).*$ matches Netcool Tool.
  • ^((.*?ool){2,5}) [FL].*$ matches Netcool Tool Cool Fool.
  • ^((.*?ool){2,5}?) [FL].*$ matches Netcool Tool Cool.
{m ,} ? Matches m or more instances of the preceding atom. Matches as few instances as possible. Given an input string of Netcool Tool Cool Fool Library:
  • ^((.*?ool){2,}).*$ matches Netcool Tool Cool Fool.
  • ^((.*?ool){2,}?).*$ matches Netcool Tool.
  • ^((.*?ool){2,}) [FL].*$ matches Netcool Tool Cool Fool.
  • ^((.*?ool){2,}?) [FL].*$ matches Netcool Tool Cool.