Quantifiers
Quantifiers say how many times the previous item repeats: * zero or more, + one or more, ? zero or one, {n} exactly n, {n,} n or more, {n,m} between n and m. They are greedy (take as much as possible) unless followed by ? which makes them lazy.
Syntax
x* x+ x? x{n} x{n,} x{n,m} lazy: x*? x+? x{n,m}?| Part | What it is |
|---|---|
* | zero or more times |
+ | one or more times |
? | zero or one time (optional) |
{n} | exactly n times |
{n,} | at least n times |
{n,m} | between n and m times, inclusive |
Examples
"ac abc abbc abbbc abbbbc".match(/ab{2,3}c/g)Result: ["abbc", "abbbc"]
"color colour".match(/colou?r/g)Result: ["color", "colour"]
/^\d{3}-\d{4}$/.test("555-1234")Result: true
["aaa", "baaa"].map(s => s.match(/a*/)[0])Result: ["aaa", ""]
* can match nothing: on baaa it succeeds with an empty match at position 0.
Common mistakes
- Writing {2, 3} with a space: JavaScript treats it as the literal text {2, 3} and the pattern silently never matches.
- Using * when you mean +: \d* matches the empty string, so a check like /^\d*$/ accepts "".
- Applying a quantifier to a sequence without a group: ab+ repeats only the b; (?:ab)+ repeats ab.
- Letting .* run past the target; use a lazy .*? or a negated class like [^,]* to stop at the right place.
Practice Quantifiers
These drills check your answer on live data, free, no account needed.
- Counted repeats: 3 to 5 digitsThe whole line must match. Match lines made of 3, 4 or 5 digits and nothing else.
- One or more: goal, gooal, goooalThe whole line must match. Match g, then one or more o characters, then al. So goal, gooal and goooooal match, but gal does not.
- Optional letter: color or colourThe whole line must match. Match the American spelling color and the British spelling colour only.
Questions
What does {1,} mean in regex?
One or more, the same as +. {0,} is the same as *, and {0,1} is the same as ?.
What is the difference between ? and * in regex?
? allows zero or one occurrence; * allows zero or any number. colou?r matches color and colour but not colouur; colou*r matches all three.
Is there a maximum repeat count?
Engines allow large counts (JavaScript and PCRE accept up to about 65535 or more), but very large bounded repeats can make the pattern slow. Prefer + or * with a sensible anchor.
Related
- Lazy vs greedyHow greedy quantifiers overshoot, how adding ? makes them lazy, why a negated class is often better than .*?, and the performance and newline traps.
- Optional with ?How ? makes a character optional, making a whole sequence optional with a group, what the capture holds when the group is absent, and the ? that means lazy.
- Capture groupsHow parentheses capture text, reading groups in JavaScript via match, matchAll and exec, reusing them with $1 in replace, and the g trap that loses groups.
- Character classesWhat a character class matches, how ranges and negation work, what \d \w \s and their uppercase opposites mean, and what the dot does and does not match.