本页面有中文版。
Cette page est disponible en français.
Esta página está disponible en español.

Quantifiers

Control how many times something repeats — from "maybe once" to "exactly three" — with ?, *, +, {n,m} and their greedy or lazy forms.

Read the rules: Quantifiers in the Guide →Drill it: Quantifier quarry →

What you'll learn

Zero or more One or more Optional {n} repetition Greedy vs lazy

Steps · 13

  1. 01How many?Briefing
  2. 02Zero or moreHunt
  3. 03One or moreHunt
  4. 04OptionalHunt
  5. 05Exactly nHunt
  6. 06n or moreHunt
  7. 07A rangeHunt
  8. 08Repeat a classHunt
  9. 09Combining piecesHunt
  10. 10Greedy by defaultHunt
  11. 11Make it lazyHunt
  12. 12Golf: whole numbersHunt
  13. 13Quantifiers masteredBriefing

Regex quantifiers: ?, *, + and {n,m}

A quantifier tells a regex how many times the item before it may repeat. Without one, every letter, dot or class matches exactly once. With one, a single piece can stretch to cover a run of characters, or become optional.

There are four forms to know. ? means zero or one, so it marks something as optional. * means zero or more and + means one or more. Curly braces give exact counts: {3} is exactly three, {2,} is two or more and {1,3} is between one and three. A quantifier works on a single letter, on a class such as [a-z], or on a group in brackets.

By default quantifiers are greedy: they take as many characters as they can and give some back only if the rest of the pattern needs them. Put a ? after a quantifier, as in +? or *?, and it becomes lazy, taking as few as possible. In a hunt, quantifiers let one short pattern catch words of different lengths while still sparing the ones that fall outside the count.

Examples

  1. /go+al/

    Catches

    • goal
    • gooooal

    Spares

    • gal
    • gaol

    + needs at least one o but allows as many as you like.

  2. /https?:/

    Catches

    • http:
    • https:

    Spares

    • htt:
    • ftp:

    ? makes the s optional, so both prefixes fit.

  3. /lo{2,3}p/

    Catches

    • loop
    • looop

    Spares

    • lop
    • loooop

    Braces set a range: two or three o's between the l and the p, no more and no fewer.

  4. /\d*\.\d+/

    Catches

    • .5
    • 3.14
    • 10.0

    Spares

    • 3.
    • 314

    * lets the whole-number part be missing, while + insists on at least one digit after the point.

Common mistakes

  • Expecting a quantifier to repeat a whole word. ha+ repeats only the a (haaa); wrap the part in a group, (ha)+, to repeat haha.
  • Letting a greedy `. * run too far. On "a" and "b", the pattern ".*" spans from the first quote to the last; use ".*?" or "[^"]*"` to stop at the nearest one.
  • Forgetting that * can match nothing. x* matches every string, even one with no x at all, so use + when at least one copy is required.

Read the rules: Quantifiers in the Guide →Drill it: Quantifier quarry →

Read more: Greedy vs lazy quantifiers: why .* eats too much →