Matching characters
Quantifiers
Goal: Repeat parts of a pattern with ?, *, + and {n,m} · 9 min
A quantifier says how often the thing directly before it may repeat.
| quantifier | meaning | example |
|---|---|---|
? | 0 or 1 time (optional) | colou?r matches "color" and "colour" |
* | 0 or more times | ab*c matches "ac", "abc", "abbbc" |
+ | 1 or more times | \d+ matches "7" and "2024" |
{3} | exactly 3 times | \d{3} is three digits |
{2,4} | between 2 and 4 times | \w{2,4} |
{2,} | at least 2 times | \d{2,} |
A quantifier applies only to the single character, class or group immediately to its left: ab+ means "a, then one or more b", not "one or more of ab". Use parentheses to repeat several characters: (ab)+ (next lessons).
Quantifiers are greedy: they take as much text as possible. In "aaaa", a+ matches all four letters.
Worked example: A German postcode
- A German postcode has exactly five digits.
- Pattern:
\d{5}. - In "10115 Berlin" the match is "10115".
console.log("10115 Berlin".match(/\d{5}/)[0]);Output:
10115