JavaScript Regex Quantifiers and Greedy Matching
Quick answer
Quantifiers describe how often the preceding atom or group may repeat. Greedy matching tries more repetitions first; lazy matching tries fewer first.
How it works
* means zero or more, + one or more, ? zero or one. {n}, {n,} and {n,m} express exact, minimum and bounded repetition. Append ? to a quantifier for lazy matching. Both strategies may backtrack as needed to satisfy later pattern requirements.
console.log(/a{2,4}/.exec("aaaaa")[0], /a{2,4}?/.exec("aaaaa")[0]);Expected output in Node.js:
aaaa aaThe greedy match first takes four; the lazy match first takes two.
console.log(/ab*c/.test("ac"), /ab+c/.test("ac"));Expected output in Node.js:
true falseStar allows zero b characters; plus requires one.
Common mistakes
Lazy does not mean always one match or always faster. Bound input sizes and avoid unnecessary ambiguity.
Practice
Extract the shortest and longest allowed run of repeated letters from a fixed string.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
JavaScript Regex Quantifiers and Greedy Matching — Knowledge Check
Apply the taught concept and predict the output.
Which quantifier means exactly three repetitions?
Which pattern permits zero or more x characters?
What does a question mark following a quantifier change?
What is the exact console output in JavaScript Regex Quantifiers and Greedy Matching example 1?
console.log(/a{2,4}/.exec("aaaaa")[0], /a{2,4}?/.exec("aaaaa")[0]);What is the exact console output in JavaScript Regex Quantifiers and Greedy Matching example 2?
console.log(/ab*c/.test("ac"), /ab+c/.test("ac"));