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

Zero or One: ?

~6 min · quantifier, optional

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

Make the previous thing optional

? means "the previous element, 0 or 1 times." In other words: optional. colou?r matches both color and colour — the u can be there or not.

This is a hugely common pattern. Half the spelling variants in the world are handled with one well-placed ?.

Common uses

  • Optional protocol: https?://example.com matches both http:// and https:// versions.
  • Optional sign: -?\d+ matches signed or unsigned integers.
  • Optional country code: (\+1)? \d{3}-\d{4}
  • British vs American spelling: analy[sz]e, colou?r, cent(er|re).

? has a SECOND meaning (preview of lesson 7)

Ahead-of-time warning: when ? appears immediately AFTER another quantifier, it changes meaning. *?, +?, ??, {n,m}? are all lazy quantifiers (covered in lesson 7). The same character has two roles depending on context. Don't confuse x? (optional x) with x*? (lazy 0-or-more).

Code

? for optional pieces·python
import re

# Optional 'u' — color OR colour
re.findall(r'colou?r', 'color colour colur')
# ['color', 'colour']  — colur (one u + r) matches as colour

# Optional protocol
re.findall(r'https?://[\w.]+', 'visit http://a.com and https://b.com')
# ['http://a.com', 'https://b.com']

# Optional sign
re.findall(r'-?\d+', '-5 and 7 and -100')
# ['-5', '7', '-100']

# British vs American spelling
re.findall(r'analy[sz]e', 'analyze the analyse')
# ['analyze', 'analyse']

External links

Exercise

Write one pattern that matches all four spellings: 'organize', 'organise', 'organization', 'organisation'. Test it. Then add the British 'organis' alone (no suffix) and notice if your pattern accidentally matches it.

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.