TExcelTAD
Home › Regular Expressions › Quantifiers

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 ?

regex · try it yourself
/ab*c/g
ac abc abbbc adc
3 matches
#1 "ac" at index 0
#2 "abc" at index 3
#3 "abbbc" at index 7
regex · try it yourself
/ab+c/g
ac abc abbbc adc
2 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:

regex · try it yourself
/-?\d+/g
Temperatures: 12, -3, 0, -15
4 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:

regex · try it yourself
/0\d{9}/g
Call 0912345678 or 091234 or 09123456789
2 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.

regex · try it yourself
/\b\d{2,3}\b/g
1 22 333 4444
2 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:

regex · try it yourself
/(?:ha)+/g
haaa hahaha
2 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:

regex · try it yourself
/\d*/g
a1b
4 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

js · try it yourself
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?

  1. ggle and gogle
  2. gogle, google, gooogle
  3. Only google
  4. gle

What does \d{3,} mean?

  1. Up to 3 digits
  2. Exactly 3 digits
  3. 3 or more digits
  4. 3 digits or a comma

In /ab?/, what does the ? apply to?

  1. ab
  2. b only
  3. a only
  4. The whole regex