Quantifiers

2 min read ·

Quantifiers control how many times a character or pattern should repeat. They are essential for building flexible and powerful regex patterns.

Question Mark ?

Matches zero or one occurrence of the previous character.
Matches:
  • color
  • colour

Curly Braces { }

Curly braces define exact or range of repetitions.

Exact Number

Matches:
  • 123
  • 123
  • 123

Range

Matches:
  • 123
  • 1234
  • 12345

Minimum Only

Matches numbers with 3 or more digits.

Note

Quantifiers always apply to the character or pattern just before them.


Greedy vs Non Greedy

By default, quantifiers are greedy, meaning they match as much as possible.

Greedy Matching

Output:
  • <tag>content</tag>

Non Greedy Matching

Add ? after quantifier to make it non greedy.
Output:
  • <tag>
  • </tag>

Pro Tip

Use non greedy matching when working with HTML or nested patterns.


Important Understanding

  • ? makes pattern optional
  • { } controls repetition count
  • Greedy matches maximum
  • Non greedy matches minimum

Caution

Greedy patterns can capture more data than expected, especially in long strings.


Exercise

  • Match words with optional characters using ?
  • Match digits of length 4 to 6 using { }
  • Try greedy and non greedy matching on tags