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

One or More: +

~6 min · quantifier, plus

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

The 'at least one' quantifier

+ is *'s stricter sibling. Same idea — repeat the previous element — but the minimum is 1, not 0. \d+ matches "one or more digits." \d* matches "zero or more digits." That single difference changes everything when you're validating input.

Pattern a+ matches a, aa, aaa... but NOT the empty string. Pattern \s+ matches one or more whitespace characters; if there's no whitespace, no match.

The default for 'a real value here'

Whenever you mean "there should be content here," reach for + instead of *. The most common production bug from * is accepting empty input. + prevents it for free.

Same syntax rules as *

+ binds to the immediately preceding element, exactly like *. ab+ repeats only b. (ab)+ repeats the whole group.

Code

+ vs *·python
import re

# + requires at least one
re.findall(r'a+', 'b aa aaa baaab')
# ['aa', 'aaa', 'aaa']

# Empty input — + fails, * succeeds
bool(re.fullmatch(r'a+', ''))   # False
bool(re.fullmatch(r'a*', ''))   # True (the source of many bugs)

# Common pattern: 'a non-empty word'
re.findall(r'\w+', 'hello   world  ')
# ['hello', 'world']  — empty runs of nothing don't count

# Group + repeats the group
re.findall(r'(ha)+', 'haha hahaha ohai')
# ['ha', 'ha']

External links

Exercise

Take a form field validator regex you have lying around. Audit every * in it: did the author mean "zero or more is fine" or "at least one"? Replace any wrong ones with +.

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.