RegexBuilder
← Back to the tools
🔁

Regex Quantifiers: *, +, ? and {n,m} Made Simple

A quantifier attaches to the thing before it and says how many times it repeats. a* means "any number of a", a+ means "one or more", a? means "zero or one". Everything about repetition in regex flows from these three signs and the braces.

The three everyday quantifiers

* = zero or more (you might have none, you might have many). + = one or more (at least one). ? = zero or one (optional). In https?, the ? makes the s optional, so it matches both http and https.

Braces for exact counts

{3} means exactly three. {3,} means three or more. {2,5} means between two and five. ZIP codes are \d{5}; credit cards are four groups of \d{4}.

Attach the quantifier to the right thing

A quantifier applies to the single character, class or group directly before it. To repeat a whole phrase you must wrap it in a group: (ab)+ matches ab, abab, ababab. Without the group, ab+ means an a followed by one or more b.

Greedy vs lazy

By default quantifiers are greedy: they take as much as they can. .* in <.*> will swallow the whole line. Adding a ? after the quantifier makes it lazy: <.*?> stops at the first >. Choose lazy when you want the smallest match.

Pitfalls

A quantifier with nothing before it is an error. And in many engines {3,2} (min greater than max) is invalid — RegexBuilder's validator flags these for you before you ship a broken pattern.

Test and explain patterns free