Skip to main content

Greedy / Lazy Quantifiers

Regular Expressions: Greedy / Lazy Quantifiers


Can you explain the difference between greedy and lazy quantifiers?

View Answer:
Interview Response: Quantifiers are Greedy by default. Greedy quantifiers seek the longest text that meets a particular pattern. Greedy quantifiers scan the whole string before attempting any match. If the full text does not match, delete the last character and try again until a match gets discovered. A lazy (also known as non-greedy or hesitant) quantifier always tries to repeat the sub-pattern as few times as feasible before expanding to longer matches. In general, a lazy pattern matches the smallest feasible string. To make quantifiers lazy, attach (?) to the current quantifier, for example, +?, {0,5}? We should emphasize that lazy quantifiers are capable of failing.

The notion of greedy/lazy quantifiers only exists in backtracking regex engines. In non-backtracking regex engines or POSIX-compliant regex engines, quantifiers only specify the repetition's upper and lower bound without specifying how to find the match.

Code Example:

// Greedy Quantifier
let regexp = /".+"/g;
let str = 'a "witch" and her "broom" is one';
alert(str.match(regexp)); // "witch" and her "broom"

// Lazy Quantifier
let regexp = /".+?"/g;
let str = 'a "witch" and her "broom" is one';

alert(str.match(regexp)); // "witch", "broom"