Greedy and lazy quantifiers
All the quantifiers that we discussed so far are greedy. A greedy quantifier starts looking at the entire string for a match. If there are no matches, it removes the last character in the string and reattempts the match. If a match is not found again, the last character is again removed and the process is repeated until a match is found or the string is left with no characters.
The \d+
pattern, for example, will match one or more digits. For example, if your string is 123
, a greedy match would match 1
, 12
, and 123
. Greedy pattern h
.+l
would match hell
in a string hello
—which is the longest possible string match. As \d+
is greedy, it will match as many digits as possible and hence the match would be 123
.
In contrast to greedy quantifiers, a lazy quantifier matches as few of the quantified tokens as possible. You can add a question mark (?
) to the regular expression to make it lazy. A lazy pattern h.?l
would match hel
in the string hello
—which is the shortest possible...