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.
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 :
|
+? |
Matches one or more instances of the preceding atom. Matches as few instances as possible. | Given an input string of little :
|
?? |
Matches zero or one instance of the preceding atom. Matches as few instances as possible. | .??b matches ab in abc ,
and b 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 :
|
{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 :
|