C.W.K.
Stream
Lesson 10 of 12 · published

Common Quantifier Mistakes

~8 min · mistakes, debugging

Level 0Pattern-Curious
0 XP0/90 lessons0/15 achievements
0/100 XP to next level100 XP to go0% complete

The five mistakes everyone makes once

1. Using * when you meant +. The validator accepts empty input. Fix: use + when content is required.

2. Greedy .* for between-marker extraction. Eats past your intended endpoint. Fix: lazy .*? or negated class [^X]*.

3. \d+ at end of pattern with no anchor. Matches partial numbers. Fix: anchor with \b or $.

4. ? applied to the wrong thing. foo?bar makes the SECOND o optional, not 'foo'. To make 'foo' optional, group it: (foo)?bar.

5. {3,} with whitespace. {3, } with a space is interpreted as literal text in some flavors. Always tight: {3,}.

Debugging quantifier issues

When a pattern "works on test data but fails in production," the cause is almost always one of:

  • Unanchored quantifier matching less than you expected.
  • Greedy quantifier eating past the intended boundary.
  • * happily matching empty input that test data didn't include.

Add temporary anchors and test against the most adversarial input you can think of (empty string, very long string, only one character, all delimiters and no content).

Code

The five common mistakes·python
import re

# Mistake 1: * accepts empty
bool(re.fullmatch(r'\d*', ''))   # True (probably wrong)
bool(re.fullmatch(r'\d+', ''))   # False (probably right)

# Mistake 2: greedy .* eats too much
re.findall(r'".*"', '"a" or "b"')  # ['"a" or "b"']
re.findall(r'"[^"]*"', '"a" or "b"')  # ['"a"', '"b"']

# Mistake 3: unanchored \d+
re.findall(r'\d+', 'order #1234X567 cost $99')
# ['1234', '567', '99']  — splits 1234X567

# Mistake 4: ? on wrong character
re.findall(r'foo?bar', 'fobar foobar fooobar')
# ['fobar', 'foobar']  — only 2nd 'o' is optional
re.findall(r'(foo)?bar', 'bar fobar foobar')
# ['', '', 'foo']  — full 'foo' optional

# Mistake 5: {n, m} with space (silent failure in some flavors)

External links

Exercise

Find a quantifier in your codebase. Test it against five adversarial inputs (empty, just whitespace, very long, all delimiters, exactly one character). Note any surprises and fix them.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.