JavaScript Reference ยท RegExp
Regular expression quantifiers
Reference for JavaScript regex quantifiers: star, plus, question mark and {n,m} repetition, greedy versus lazy matching, and how to avoid slow patterns.
A quantifier says how many times the thing before it may repeat. \d+ means one or more digits, colou?r makes the u optional, and \d{3} demands exactly three digits. The quantifier applies to the single item just before it: a character, a class like [a-z], or a group in parentheses.
By default quantifiers are greedy: they take as much text as they can and give some back only if the rest of the pattern would fail. Adding ? after a quantifier makes it lazy: it takes as little as possible. This is a concept page; the examples show the difference.
"<b>one</b><b>two</b>".match(/<b>.*<\/b>/)[0]; // "<b>one</b><b>two</b>" "<b>one</b><b>two</b>".match(/<b>.*?<\/b>/)[0]; // "<b>one</b>"
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Quantifier forms
| Greedy | Lazy | Meaning |
|---|---|---|
* |
*? |
Zero or more. |
+ |
+? |
One or more. |
? |
?? |
Zero or one (optional). |
|
Exactly n. |
|
{n,} |
{n,}? |
n or more. |
{n,m} |
{n,m}? |
From n to m. |
Usage notes
- Greedy is the default and usually what you want for things like
\d+. Lazy matters mostly with.and delimiters, such as quotes or tags. - Prefer a negated class over lazy when you can:
"[^"]*"is clearer and faster than".*?", and it cannot run past the closing quote. *can match nothing./\d*/matches at every position of "abc" with an empty string, which surprises people who expect it to find numbers. Use+to require something.{n,m}has no spaces:{1, 3}is treated as literal text. A{that is not a valid quantifier is literal in non-Unicode mode but a syntax error withuorv.- A quantifier applies to one item.
ab+repeats onlyb; use(?:ab)+to repeat both. - A group repeated by a quantifier records only its last repetition in a capture.
- Possessive quantifiers and atomic groups (such as
a++) do not exist in JavaScript. - Catastrophic backtracking: nested open-ended repeats like
(a+)+$or(.*)*can take exponential time when the match fails. Simplify the pattern, make alternatives exclusive, and limit input length. - Large counts such as
{1,100000}are allowed, but patterns with huge counts may be slow.
Browser support
Quantifiers work in every browser and runtime.