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 ...

Get JavaScript: Functional Programming for JavaScript Developers now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.