appzasGamesToolsDevLearnCheat sheetsQuick calcsConvertersReferenceNetworkTimeCalculatorsCompareLLM prices

Quantifiers and anchors

Lesson 2 of 39 minBeginner

Repeat things and pin matches to the start or end.

QuantifierMeaning
*Zero or more
+One or more
?Zero or one (optional)
{3}Exactly 3
{2,4}Between 2 and 4
{2,}2 or more

\d{3}-\d{4} matches 555-1234. colou?r matches both color and colour.

Anchors

  • ^ start of the text (or line).
  • $ end of the text (or line).
  • \b a word boundary.

Without anchors a pattern can match part of the text. \d{5} finds five digits inside "ab12345cd". To require the whole value to be a ZIP code, write ^\d{5}$.

Greedy and lazy

Quantifiers are greedy: they take as much as possible. On <b>one</b><b>two</b>, the pattern <b>.*</b> matches the entire string, while the lazy <b>.*?</b> matches each tag pair separately. Add ? after the quantifier to make it lazy.

CarefulNever parse full HTML with regex. Use a parser. Regex is fine for simple, predictable text.

Test yourself

Answer all the questions, then check them. Finish with every answer right to mark the lesson as done.

1. Which pattern matches exactly a 5-digit ZIP code and nothing else?
2. What does colou?r match?
3. What is the difference between .* and .*? ?
4. What does \d{2,4} match?

Key terms