Learn regular expressions · Lesson 3

Repetition

A quantifier after something in a pattern says how many times it may come. There are four:

  • ? once or not at all
  • * any number of times, none included
  • + once or more
  • {n,m} at least n and at most m times; {n} exactly n, {n,} n or more

?: optional

colou?r is colo, an optional u, and r: both spellings.

/colou?r/g2 matches
color, colour, colouur
Try it in Dotstar →

* and +: as many as there are

go+al is a g, one o or more, and al. With * instead, gal matches too, with no o at all:

/go+al/g2 matches
gal, goal, gooooal
Try it in Dotstar →
/go*al/g3 matches
gal, goal, gooooal
Try it in Dotstar →

{n,m}: a count

Braces give the numbers: \d is a digit (the next lesson has more like it), so \d{4} is four digits, and \d{2,3} two or three.

/\d{4}-\d{2}-\d{2}/g2 matches
Due 2026-10-24, paid 2026-11-02.
Try it in Dotstar →

What a quantifier repeats

A quantifier applies to the one thing right before it: a character, an escape like \d, a character class, or a group. So ab+ is an a followed by b's, not ab repeated: that needs a group, (ab)+, which a later lesson is about.

/ab+/g4 matches
ab abbb abab
Try it in Dotstar →

As many as it can

Quantifiers are greedy: they take as many repetitions as they can, and give some back only if the rest of the pattern can’t match otherwise. That’s why go+al takes every o. It matters most with .*, “anything, any number of times”, which can take far more than you meant; a later lesson shows the lazy forms, *? and +?, which take as few as they can.