DevLab
Regex

Regex Quantifiers: Complete Guide

Master greedy, lazy, and possessive quantifiers in regular expressions with practical examples.

Basic Quantifiers

Quantifiers specify how many times a pattern element should match. They apply to the character, group, or character class immediately before them.

  • * — Zero or more times
  • + — One or more times
  • ? — Zero or one time (optional)
  • {n} — Exactly n times
  • {n,} — n or more times
  • {n,m} — Between n and m times

Greedy Quantifiers (Default)

By default, quantifiers are greedy — they try to match as much text as possible while still allowing the overall pattern to match. Think of them as "try to grab everything, then give back what you must."

The pattern ".+" applied to "hello" "world" matches the entire string "hello" "world", not just "hello".

Lazy Quantifiers

Add ? after any quantifier to make it lazy: *?, +?, ??, {n,m}?. Lazy quantifiers try to match as little as possible.

The pattern ".+?" applied to "hello" "world" now matches "hello" and then "world" separately.

Practical Examples

HTML tag content: <[^>]+>(.*?)</ — The lazy .*? prevents matching across multiple tags.

Quoted strings: "[^"]*" — Better than ".+?" because it uses a negated character class, which is clearer and faster.

Optional whitespace: \s* — Zero or more spaces, useful for flexible parsing.

Practice with these tools

More Learning Topics