Quantifiers
Control repetition with star, plus, question mark and braces, build patterns for codes and dates, and see how greedy quantifiers grab as much as they can.
Welcome back!
Step 1 of 14Learn
How many times?
A US ZIP code is five digits. You could write \d\d\d\d\d, but what about a phone extension that might be two, three or four digits? Quantifiers say how many times the previous item may repeat:
| Quantifier | Meaning | Example | Matches |
|---|---|---|---|
* | zero or more | ab*c | "ac", "abc", "abbbc" |
+ | one or more | ab+c | "abc", "abbbc", not "ac" |
? | zero or one (optional) | colou?r | "color", "colour" |
{n} | exactly n | \d{5} | "90210" |
{n,m} | between n and m | \d{2,4} | "42", "123", "2026" |
{n,} | n or more | \w{8,} | words of 8+ characters |
A quantifier applies to the single item just before it: one character, one class, one escape, or one group in parentheses. So ab+ means "a, then one or more b," not "one or more ab." To repeat a sequence, wrap it in parentheses: (ab)+ matches "ab," "abab," "ababab."
With quantifiers, the date pattern reads naturally: \d{4}-\d{2}-\d{2} is four digits, a dash, two digits, a dash, two digits.
Step 2 of 14Compare
Quantifiers by minimum and maximum
| Aspect | Minimum | Maximum | Example |
|---|---|---|---|
| ? | 0 | 1 | colou?r: color, colour |
| * | 0 | no limit | ab*c: ac, abc, abbbc |
| + | 1 | no limit | \d+: 7, 42, 2026 |
| {3} | 3 | 3 | \d{3}: 555 |
| {2,4} | 2 | 4 | \d{2,4}: 12, 123, 1234 |
Step 3 of 14Practice · Match the pairs
Match each pattern to a string it matches completely.
Tap an answer, then tap the place where it belongs (or drag it there).
go+glego*glecolou?r\d{3}-\d{4}
Step 4 of 14Learn
Building a pattern piece by piece
Real patterns are built incrementally. Let's describe a product code like "SKU-AB-0042": the text SKU, a dash, two uppercase letters, a dash, four digits.
- Literal start:
SKU- - Two uppercase letters:
[A-Z]{2} - A dash:
- - Four digits:
\d{4}
Together: SKU-[A-Z]{2}-\d{4}.
Now a new requirement: older codes have no letter block, like "SKU-0042." Make the letter block and its dash optional by grouping them: SKU-([A-Z]{2}-)?\d{4}. The question mark applies to the whole group.
US ZIP codes have an optional four-digit extension: "90210" or "90210-1234." The pattern is \d{5}(-\d{4})?.
Work this way every time: write the simplest piece, test it, add the next piece, test again. Test both strings that should match and strings that shouldn't. "SKU-AB-042" (only three digits) and "SKU-ab-0042" (lowercase) should both fail. A pattern that matches everything you want is only half done until you've checked that it rejects what you don't want.
Step 5 of 14Try the calculator
How many strings can a pattern match?
A pattern like [A-Z]{3}\d{4} (three uppercase letters, four digits) matches 263 × 104 different strings. Change the counts to see how quickly the possibilities grow, which matters for codes, passwords and IDs.
- Possible strings
- 175,760,000
- Possible strings if letters may be upper or lower case
- 1,406,080,000
Step 6 of 14Practice · Work it out
A license plate format is described by [A-Z]{2}\d{3}: two uppercase letters followed by three digits. How many different plates does this pattern allow?
Step 7 of 14Learn
Greedy by default
Quantifiers are greedy: they match as much as they possibly can, then give back characters only if the rest of the pattern needs them. Usually that's what you want. Sometimes it's a nasty surprise.
Take the HTML snippet <b>bold</b> and <i>italic</i> and the pattern <.+>, intended to match one tag. The .+ starts after the first < and greedily runs to the end of the line. Then the engine needs a >, so it backtracks, giving characters back one at a time from the end, until it finds the last >. The match is the entire string, from the first < to the final >, not just <b>.
Two fixes:
- Lazy quantifiers add a question mark:
*?,+?,??,{n,m}?. They match as little as possible.<.+?>matches<b>, then</b>, and so on. - Negated classes describe what may appear in between:
<[^>]+>means "a<, then characters that are not>, then>." It can't run past a>, so it never overmatches, and it avoids backtracking altogether.
Many experienced regex writers prefer the negated-class version. It states the intent precisely and is often faster. You'll return to backtracking and its performance traps in module 4.
Step 8 of 14Practice · Diagram
Greedy <.*> on "<b>bold</b>"
Which step makes the match swallow the whole snippet instead of just <b>?
Tap the shape that answers the question, then press Check.
- < matches the first <
- .* eats to the end
It grabs b>bold</b>, the whole rest of the text.
- Need a >: give back
The engine backtracks one character at a time until > can match.
- Match: <b>bold</b>
The last > in the text, not the first one.
Step 9 of 14Note
Step 10 of 14Practice · True or false
A quantifier placed after a character class, as in [0-9]+, repeats the whole class, so the pattern can match "4721" with different digits in each position.
Step 11 of 14Practice · Code challenge
Write isZip(text) that returns true only if the entire string is a US ZIP code: five digits, optionally followed by a dash and four more digits ("90210" or "90210-1234"). The anchors ^ and $ (start and end of string) are given in the starter; fill in the middle.
isZip("90210")isZip("90210-1234")isZip("9021")isZip("90210-12")isZip("902101")isZip("ABCDE")
Step 12 of 14Note
Step 13 of 14Note
Step 14 of 14Practice · Choose one
Which pattern matches a word of exactly 5 to 8 lowercase letters, such as "apple" or "elephant", when anchored to the whole string?
Lesson complete!