Quantifiers
A quantifier says how many times the thing right before it may repeat. "The thing before it" can be a single character, a class, an escape like \d, or a whole group in parentheses.
| Quantifier | Meaning | Example | Matches |
|---|---|---|---|
* |
0 or more | ab*c |
ac, abc, abbbc |
+ |
1 or more | ab+c |
abc, abbbc (not ac) |
? |
0 or 1 (optional) | colou?r |
color, colour |
{n} |
exactly n | \d{4} |
2025 |
{n,} |
n or more | \d{2,} |
12, 12345 |
{n,m} |
between n and m | \d{2,3} |
12, 123 |
*, + and ?
/ab*c/g
ac abc abbbc adc3 matches
#1 "ac" at index 0
#2 "abc" at index 3
#3 "abbbc" at index 7
/ab+c/g
ac abc abbbc adc2 matches
#1 "abc" at index 3
#2 "abbbc" at index 7
? makes the previous item optional. It is perfect for spelling variants and optional signs:
/-?\d+/g
Temperatures: 12, -3, 0, -154 matches
#1 "12" at index 14
#2 "-3" at index 18
#3 "0" at index 22
#4 "-15" at index 25
Counted repetition with braces
Braces give exact control. A Vietnamese-style mobile number, for instance, is 0 followed by nine digits:
/0\d{9}/g
Call 0912345678 or 091234 or 091234567892 matches
#1 "0912345678" at index 5
#2 "0912345678" at index 29
Look closely at the second match: it is the first ten digits of an eleven-digit number. A quantifier alone does not stop the engine from matching part of a longer run. Anchors and word boundaries (upcoming lessons) fix that: \b0\d{9}\b.
/\b\d{2,3}\b/g
1 22 333 44442 matches
#1 "22" at index 2
#2 "333" at index 5
Note:
{,5}(no lower bound) is not a quantifier in JavaScript — it's treated as literal text. Write{0,5}. Python 3 accepts{,5}.
Quantifying a group
A quantifier applies only to the single item before it. ha+ repeats the a; (ha)+ repeats the pair:
/(?:ha)+/g
haaa hahaha2 matches
#1 "ha" at index 0
#2 "hahaha" at index 5
((?:...) is a group that doesn't capture — you will meet it soon. A plain (ha)+ would work the same but also report a group.)
Quantifiers can match zero characters
* and ? are happy to match nothing. With the g flag that can produce empty matches at positions where nothing else fits:
/\d*/g
a1b4 matches
#1 "" at index 0
#2 "1" at index 1
#3 "" at index 2
#4 "" at index 3
That is rarely what you want; use + when at least one character is required.
In code
const ids = ["A-1", "AB-123", "ABC-1234", "A-12345"];
const re = /^[A-Z]{1,3}-\d{1,4}$/;
for (const id of ids) console.log(id.padEnd(9), re.test(id));A-1 true
AB-123 true
ABC-1234 true
A-12345 false
Test yourself
Which strings does /^go+gle$/ match?
ggleandgoglegogle,google,gooogle- Only
google gle
What does \d{3,} mean?
- Up to 3 digits
- Exactly 3 digits
- 3 or more digits
- 3 digits or a comma
In /ab?/, what does the ? apply to?
abbonlyaonly- The whole regex