Optional Elements and the Question Mark
What you'll learn: How to use the ? operator in regular expressions to make a pattern element appear zero or exactly one time.
The Core Idea
In regular expressions, the question mark (?) makes whatever comes before it optional—it means "the preceding element may appear once, or not at all." This is perfect for patterns where something might be present but isn't required.
Think of it like a coat on a slightly chilly day: you might wear it, or you might not, but you'll never need two coats at once. That's zero-or-one occurrence.
How It Works
The ? operator applies to the element immediately before it:
a?matches eitheraor the empty string (nothing)colou?rmatches bothcolorandcolour(theuis optional)(ab)?cmatches bothcandabc(the entire groupabis optional)
Unlike * (zero-or-more) or + (one-or-more), the ? is limited to at most one occurrence. It's the most restrictive repetition operator.
Common Patterns
Optional elements appear frequently in real-world text:
- Phone numbers:
\(?\d{3}\)?(area code parentheses are optional) - Titles:
Dr\.? Smith(period after "Dr" may or may not exist) - Protocols:
https?://(matches bothhttp://andhttps://)
Formal Definition
If r is a regular expression, then r? denotes the language L(r) ∪ {ε}, where ε is the empty string. You're adding the possibility of matching nothing to whatever r already matched.
Key Takeaway: The ? operator makes the preceding element optional, allowing exactly zero or one occurrence—use it when something may or may not be present in your pattern.