Quantifiers and anchors
Repeat things and pin matches to the start or end.
| Quantifier | Meaning |
|---|---|
* | 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).\ba 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.