Asterisk * — Zero or More
Matches the previous token zero or more times.
Explanation:
Matches col, cool, and coool.
Plus + — One or More
Matches the previous token one or more times
Explanation:
Matches cool but not col.
Question Mark ? — Zero or One (Optional)
Makes the previous token optional.
Explanation:
Matches both color and colour.
Exact Count {n}
Matches the previous token exactly n times
Explanation:
Matches only if there are exactly 4 digits.
At Least {n,}
Matches the previous token at least n times.
Explanation:
Matches two or more occurrences of a.
Range {n,m}
Matches the previous token between n and m times
Explanation:
Matches if a appears between 2 and 4 times.
Greedy vs Lazy Quantifiers
By default, quantifiers are greedy and try to match as much as possible.
Adding ? after a quantifier makes it lazy, matching as little as possible.
Explanation:
.*? matches the smallest possible content between < and >.
Applying Quantifiers to Groups
Quantifiers can be applied to grouped patterns.
Explanation:
Matches ab repeated 2 to 3 times.
Common Mistakes with Quantifiers
-
Forgetting that quantifiers apply only to the previous token
-
Using greedy quantifiers where lazy matching is required
-
Not anchoring patterns with
^and$for full-string validation -
Misusing
{n,m}ranges
Summary of RegExp Quantifiers
| Quantifier | Meaning |
|---|---|
* | Zero or more |
+ | One or more |
? | Zero or one |
{n} | Exactly n |
{n,} | At least n |
{n,m} | Between n and m |
*? +? | Lazy versions |
Conclusion
RegExp quantifiers in JavaScript control how many times a pattern can repeat, making regular expressions powerful for matching variable-length text. By choosing the right quantifier and understanding greedy versus lazy behavior, pattern matching becomes more accurate and reliable in JavaScript applications.