Course contentsShow
← Computer Science
Lesson 1772 of 2,87240. Theory of Computation: Regular LanguagesFree lesson

Optional Elements and the Question Mark

Use the ? operator to express optional elements and construct patterns with zero-or-one occurrences.

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 either a or the empty string (nothing)
  • colou?r matches both color and colour (the u is optional)
  • (ab)?c matches both c and abc (the entire group ab is 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 both http:// and https://)

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.