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 →
Builds on Character classes
What you'll learn
Steps · 13
- 01How many?Briefing
- 02Zero or moreHunt
- 03One or moreHunt
- 04OptionalHunt
- 05Exactly nHunt
- 06n or moreHunt
- 07A rangeHunt
- 08Repeat a classHunt
- 09Combining piecesHunt
- 10Greedy by defaultHunt
- 11Make it lazyHunt
- 12Golf: whole numbersHunt
- 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
Catches
- goal
- gooooal
Spares
- gal
- gaol
+needs at least one o but allows as many as you like.Catches
- http:
- https:
Spares
- htt:
- ftp:
?makes the s optional, so both prefixes fit.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.
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 repeathaha. - 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 →