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

Zero or More: *

~8 min · quantifier, star

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

Match the previous thing zero or more times

* is the most permissive quantifier. It says "the previous element, repeated 0 or more times." The critical word is zero* ALWAYS matches, because matching nothing satisfies it.

Pattern colou*r matches color, colour, colouur, all the way to colouuuuuuuur. The u can repeat 0 or more times.

What 'previous element' means

* applies to the immediately preceding piece, which can be:

  • A single character: ab* matches a, ab, abb, abbb...
  • A character class: [0-9]* matches an empty string or any run of digits.
  • A group: (ab)* matches an empty string, ab, abab, ababab...

The element to its LEFT — that's it. ab* repeats only the b, not ab.

The 'always matches' surprise

Because * matches zero occurrences, an unanchored pattern with only * always succeeds. re.match(r'\d*', 'hello') returns a match — an empty match at position 0. This is technically correct but rarely useful. Combine * with anchors or other elements that force at least something to match.

Code

* in action·python
import re

# Match 'colour' or 'color' (or any number of u's)
re.findall(r'colou*r', 'color colour colouuur colr')
# ['color', 'colour', 'colouuur']  — 'colr' matches too!

# * binds to the previous element only
re.findall(r'ab*', 'a ab abb abbb')
# ['a', 'ab', 'abb', 'abbb']  — only b repeats

# Group with * — the whole group repeats
re.findall(r'(ab)*', 'ab abab abc')
# ['ab', 'abab', 'ab', '']  — even empty matches!

# * always matches — even an empty string
re.match(r'\d*', 'hello').group()
# ''  (empty match at position 0)

External links

Exercise

Predict what re.fullmatch(r'a*', '') returns. Then run it. Then think about what bug this causes if a* was your password validator.

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.