Alternation: The OR Operator in Regex
Learning Objectives: By the end of this lesson, you will be able to:
- Use the pipe character (|) to create “this OR that” patterns
- Combine alternation with grouping for complex matching scenarios
- Apply alternation to match multiple word variations and formats
- Understand precedence and ordering in alternation patterns
- Build flexible patterns for real-world text variations
1. Welcome and Introduction (5 minutes)
Icebreaker Activity
Think about all the different ways people might write the word “color” - some spell it “color” (American English) while others spell it “colour” (British English). Or consider how dates can be written: “12/01/2023”, “Dec 1, 2023”, “1 December 2023”. How could you write one pattern that matches all these variations?
This is exactly what alternation solves - it lets you specify multiple alternatives in a single pattern, making your regex flexible enough to handle real-world variations!
Lesson Overview
- Duration: 55 minutes
- Prerequisites: Understanding of basic regex, metacharacters, quantifiers, and grouping
- Materials Needed: Access to regex101.com, text samples with variations
2. Learning Objectives and Session Outline (5 minutes)
What We’ll Cover Today:
- Basic Alternation - Using the pipe (|) for simple “this OR that” patterns
- Alternation with Grouping - Combining | with parentheses for complex patterns
- Multiple Alternatives - Handling more than two options
- Precedence and Ordering - Understanding how alternation affects matching
- Real-World Applications - Flexible matching for varying formats and terminology
Success Criteria:
By the end of this session, you should be able to create patterns that gracefully handle multiple variations of the same concept while maintaining precision and readability.
3. Foundation Knowledge (15-20 minutes)
What is Alternation?
Alternation uses the pipe character | to create an “either this OR that” choice in your regex pattern. It’s like giving the regex engine multiple options to try when matching text.
Real-World Analogy: Think of alternation like a restaurant menu with multiple options. Instead of ordering “exactly chicken,” you can order “chicken OR beef OR fish” - whichever one is available will satisfy your order.
Why This Matters: Real-world text is inconsistent:
- Different spellings: “color” vs “colour”
- Multiple formats: dates, phone numbers, addresses
- Synonyms: “car” vs “automobile” vs “vehicle”
- Case variations: “iPhone” vs “iphone” vs “IPHONE”
Alternation lets you handle all these variations in a single, elegant pattern.
Basic Alternation Syntax
Simple alternation: cat|dog
- Matches either “cat” OR “dog”
- No spaces around the pipe character
- First match wins (left-to-right priority)
With grouping: (cat|dog)
- Groups the alternation for use with quantifiers or other elements
- Can be captured like any other group
Complex example: (red|blue|green) car
- Matches “red car”, “blue car”, or “green car”
- The alternation only applies to the color, not the entire phrase
How Alternation Works
The regex engine tries alternatives from left to right:
- Try the first alternative
- If it matches, use it (even if a later alternative might match better)
- If it doesn’t match, try the next alternative
- Continue until one matches or all fail
Text: category
Pattern: cat|category
Result: Matches “cat” (not “category”) because “cat” is tried first and matches
Pattern: category|cat
Result: Matches “category” because it’s tried first
Key Terminology
- Alternation: The | operator that provides choices
- Alternative: Each option separated by |
- Precedence: The order in which alternatives are tried
- Greedy alternation: Takes the first match found (default behavior)
- Branch: Another term for each alternative in the pattern
4. Detailed Explanation and Examples (25-30 minutes)
Basic Alternation Examples
Let’s start with simple cases:
Text: I have a cat and a dog
Pattern: cat|dog
cat|dog
Matches: “cat” and “dog”
Text: The color is red, but I prefer blue or green
Pattern: red|blue|green
red|blue|green
Matches: “red”, “blue”, “green”
Alternation with Grouping
Grouping becomes essential when you want alternation to apply to part of a larger pattern:
Text: I like red cars and blue trucks
Without grouping: red|blue car
red|blue car
Problem: This matches “red” OR “blue car” (not what we want)
With grouping: (red|blue) car
(red|blue) car
Matches: “red car” (if it existed) and doesn’t match “blue trucks”
Better example: (red|blue) (car|truck)
(red|blue) (car|truck)
Matches: “red car”, “red truck”, “blue car”, “blue truck”
Case-Insensitive Matching with Alternation
Text: iPhone, Iphone, iphone, IPHONE
Pattern: iPhone|Iphone|iphone|IPHONE
iPhone|Iphone|iphone|IPHONE
Matches: All variations
More elegant with character classes: i[Pp]hone|iPhone|IPHONE
Actually, even better: [Ii][Pp][Hh][Oo][Nn][Ee]
But alternation is cleaner for known variations.
Alternation with Different Lengths
Text: USA, United States, United States of America
Pattern: USA|United States of America|United States
USA|United States of America|United States
Important: Put longer alternatives first! If “United States” comes before “United States of America”, it will match the shorter version first.
Correct order: United States of America|United States|USA
United States of America|United States|USA
Complex Real-World Example
Text: Contact us at (555) 123-4567 or 555.123.4567 or 555-123-4567
Pattern: \(?\d{3}\)?[-.\s]\d{3}[-.\s]\d{4}
This works but is hard to read.
With alternation: \(\d{3}\) \d{3}-\d{4}|\d{3}\.\d{3}\.\d{4}|\d{3}-\d{3}-\d{4}
\(\d{3}\) \d{3}-\d{4}|\d{3}\.\d{3}\.\d{4}|\d{3}-\d{3}-\d{4}
Explanation:
\(\d{3}\) \d{3}-\d{4}- matches “(555) 123-4567”\d{3}\.\d{3}\.\d{4}- matches “555.123.4567”\d{3}-\d{3}-\d{4}- matches “555-123-4567”
Alternation in Character Classes vs Alternation Operator
Character classes [abc] - match any single character from the set
Alternation a|b|c - match any of these complete strings
Text: cat bat rat
Pattern: [cbr]at
[cbr]at
Matches: “cat”, “bat”, “rat” (single character choice + “at”)
Pattern: c|b|rat
c|b|rat
Matches: “c” (from “cat”), “b” (from “bat”), “rat”
Common Misconceptions
-
Misconception: “Alternation finds the best match” Reality: Alternation finds the first match from left to right
-
Misconception: “Order doesn’t matter in alternation” Reality: Order is crucial - put longer/more specific patterns first
-
Misconception: “Alternation and character classes are the same” Reality:
[abc]matches one character,a|b|cmatches complete strings
5. Live Coding Demonstration (20-25 minutes)
Example 1: Date Format Matching
Text:
Meeting dates:
2023-12-01 (ISO format)
12/01/2023 (US format)
01/12/2023 (European format)
Dec 1, 2023 (Written format)
1 December 2023 (Full written)
Goal: Match all date formats
Building the Pattern:
Step 1: ISO format
\d{4}-\d{2}-\d{2}
Step 2: Numeric formats
\d{1,2}/\d{1,2}/\d{4}
Step 3: Month names (abbreviated)
(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) \d{1,2}, \d{4}
Step 4: Full month names
\d{1,2} (January|February|March|April|May|June|July|August|September|October|November|December) \d{4}
Combined pattern:
\d{4}-\d{2}-\d{2}|\d{1,2}/\d{1,2}/\d{4}|(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) \d{1,2}, \d{4}|\d{1,2} (January|February|March|April|May|June|July|August|September|October|November|December) \d{4}
Example 2: File Extension Matching
Text:
Files: document.pdf, image.jpg, photo.jpeg, data.csv, archive.tar.gz
Code: script.js, style.css, app.py, main.cpp, README.md
Goal: Match common file extensions
Pattern Building:
Step 1: Image files
\.(jpg|jpeg|png|gif|bmp)
Step 2: Document files
\.(pdf|doc|docx|txt|rtf)
Step 3: Code files
\.(js|css|py|cpp|java|html|php)
Step 4: Archive files (special case for .tar.gz)
\.tar\.gz|\.(zip|rar|7z)
Combined for image files:
\w+\.(jpg|jpeg|png|gif|bmp)$
Note: Put .tar.gz before .gz to avoid matching just the .gz part!
Example 3: Color Name Matching
Text:
CSS colors: red, blue, green, #FF0000, #00ff00, rgb(255,0,0)
Named colors: crimson, navy, forest-green, dark-blue
Variations: grey, gray, color, colour
Goal: Match different color specifications
Pattern Building:
Step 1: Basic color names
red|blue|green|yellow|orange|purple|pink|brown|black|white
Step 2: Color variations (grey/gray, colour/color)
gr[ae]y|colou?r
Step 3: Hex colors
#[0-9A-Fa-f]{6}|#[0-9A-Fa-f]{3}
Step 4: RGB colors
rgb\(\d{1,3},\d{1,3},\d{1,3}\)
Combined pattern:
#[0-9A-Fa-f]{6}|#[0-9A-Fa-f]{3}|rgb\(\d{1,3},\d{1,3},\d{1,3}\)|red|blue|green|yellow|orange|purple|pink|brown|black|white|gr[ae]y
Debugging Demonstration
Common mistake: Wrong order in alternation
cat|category
Problem: In text “category”, this matches “cat” instead of “category”
Corrected version:
category|cat
Solution: Put longer patterns first to avoid premature matching.
6. Hands-On Practice (30-40 minutes)
Exercise 1: Basic Alternation (10 minutes)
Objective: Practice simple “this OR that” patterns
Test String:
Transportation: I drive a car to work, but sometimes take the bus or train.
My friend rides a bike, and another uses a motorcycle.
Some people prefer walking or running for exercise.
In the city, you might see a taxi, uber, or subway.
Challenges:
- Match all forms of personal transportation (car, bike, motorcycle)
- Match all public transportation options (bus, train, taxi, uber, subway)
- Match exercise activities (walking, running)
- Create one pattern that matches any transportation method mentioned
Starter Patterns:
# Challenge 1: Personal transportation
car|bike|motorcycle
# Challenge 2: Public transportation
bus|train|taxi|uber|subway
# Challenge 3: Exercise activities
walking|running
# Challenge 4: All transportation (combine above)
car|bike|motorcycle|bus|train|taxi|uber|subway
Solutions:
# 1. Personal transportation
car|bike|motorcycle
# 2. Public transportation
bus|train|taxi|uber|subway
# 3. Exercise activities
walking|running
# 4. All transportation methods
car|bike|motorcycle|bus|train|taxi|uber|subway|walking|running
Exercise 2: Alternation with Grouping (15 minutes)
Objective: Combine alternation with grouping for complex patterns
Test String:
Weather reports:
It's hot and sunny today, perfect for swimming.
Tomorrow will be cold and rainy - bring an umbrella.
The weekend looks warm and cloudy with possible showers.
Next week might be cool and windy, but mostly dry.
Yesterday was freezing and snowy in the mountains.
Challenges:
- Match temperature descriptions with weather (hot sunny, cold rainy, etc.)
- Create a pattern for “temperature + and + condition”
- Match any weather condition (sunny, rainy, cloudy, windy, snowy, dry)
- Build a flexible pattern that captures both temperature and condition
Hints:
- Use grouping:
(option1|option2) and (option3|option4) - Consider word boundaries to avoid partial matches
- Think about capturing groups vs non-capturing groups
Progressive Solutions:
# Challenge 1: Temperature + weather combinations
(hot|cold|warm|cool|freezing) and (sunny|rainy|cloudy|windy|snowy)
# Challenge 2: Pattern for "temp + and + condition"
(hot|cold|warm|cool|freezing) and (sunny|rainy|cloudy|windy|snowy|dry)
# Challenge 3: Any weather condition
sunny|rainy|cloudy|windy|snowy|dry
# Challenge 4: Flexible pattern with capturing
(hot|cold|warm|cool|freezing) and (sunny|rainy|cloudy|windy|snowy|dry)
Exercise 3: Real-World Format Variations (15 minutes)
Objective: Handle multiple formats for the same type of data
Complex Data:
Contact information:
Phone: (555) 123-4567, 555.123.4567, 555-123-4567, +1-555-123-4567
Email: user@domain.com, first.last@company.org, contact_us@site-name.net
Address: 123 Main St, 456 Oak Street, 789 Pine Avenue, 321 Elm Blvd
Time: 2:30 PM, 14:30, 2:30pm, 14:30:00, 2:30:45 PM
Real-World Challenges:
- Match all phone number formats
- Match email addresses with different username styles
- Match street addresses with various street types
- Match time formats (12-hour, 24-hour, with/without seconds)
Building Approach: Start with individual formats, then combine:
# Challenge 1: Phone numbers
\(\d{3}\) \d{3}-\d{4}|\d{3}\.\d{3}\.\d{4}|\d{3}-\d{3}-\d{4}|\+1-\d{3}-\d{3}-\d{4}
# Challenge 2: Email variations
\w+@\w+\.\w+|\w+\.\w+@\w+\.\w+|\w+_\w+@\w+-\w+\.\w+
# Challenge 3: Street addresses
\d+ \w+ (St|Street|Avenue|Blvd)
# Challenge 4: Time formats
\d{1,2}:\d{2} (AM|PM)|\d{1,2}:\d{2}|\d{1,2}:\d{2}(am|pm)|\d{1,2}:\d{2}:\d{2}|\d{1,2}:\d{2}:\d{2} (AM|PM)
Extension Ideas:
- Make patterns case-insensitive where appropriate
- Add word boundaries to prevent partial matches
- Consider international variations (country codes, postal formats)
7. Common Pitfalls and Troubleshooting (10 minutes)
Frequent Mistakes
-
Problem: Wrong order causing premature matches Cause: Putting shorter alternatives before longer ones Solution: Order alternatives from longest to shortest:
category|catnotcat|category -
Problem: Forgetting to group alternation Cause:
red|blue carmatches “red” OR “blue car”, not “(red|blue) car” Solution: Use parentheses:(red|blue) car -
Problem: Alternation matching partial words Cause: Not using word boundaries with word alternatives Solution: Add
\b:\b(cat|dog)\binstead ofcat|dog -
Problem: Too many alternatives making patterns unreadable Cause: Long lists like
red|blue|green|yellow|orange|purple|pink|brown|black|whiteSolution: Consider character classes or separate patterns for different categories
Debugging Tips
- Test each alternative separately first
- Use regex101.com to see which alternative matches
- Check order - put more specific patterns first
- Consider if character classes would be simpler for single characters
- Use word boundaries when matching complete words
Performance Considerations
- Too many alternatives can slow down matching
- Order matters for performance - put most common alternatives first
- Consider if alternatives could be simplified with character classes
- Long alternation lists might be better as separate regex calls
8. Best Practices and Professional Tips (5 minutes)
Industry Standards
- Order by specificity: Put longer, more specific alternatives first
- Group when necessary: Use parentheses to control alternation scope
- Use word boundaries: Add
\bwhen matching complete words - Consider readability: Very long alternations might need refactoring
Common Patterns
# Boolean values
true|false|yes|no|on|off
# File extensions
\.(jpg|jpeg|png|gif|bmp)
# Protocols
(http|https|ftp)://
# Color variations
gr[ae]y|colou?r
# Common abbreviations
(Mr|Mrs|Ms|Dr|Prof)\.?
When to Use Alternation vs. Other Approaches
Use alternation when:
- You have distinct, known alternatives
- Alternatives are complete words or phrases
- Order matters for matching priority
Use character classes when:
- You’re matching single characters
- You have ranges of characters (a-z, 0-9)
- You need negation (everything except…)
Use quantifiers when:
- You’re dealing with repetition
- Optional elements can be handled with ?
- Variable length patterns
Next Steps in Your Learning Journey
- Learn advanced features like lookaheads and lookbehinds
- Study the interaction between alternation and capturing groups
- Explore case-insensitive flags and modifiers
- Practice with real-world data that has natural variations
9. Summary and Review (5 minutes)
Key Takeaways
- The pipe | creates choices:
cat|dogmatches either “cat” or “dog” - Order matters: Alternatives are tried left to right, first match wins
- Use grouping for scope:
(red|blue) carnotred|blue car - Longer alternatives first:
category|catnotcat|category - Add word boundaries for complete words:
\b(cat|dog)\b
Quick Review Questions
- What’s the difference between
[abc]anda|b|c? - Why might
cat|categorynot work as expected? - How do you make alternation apply to just part of a pattern?
Answers:
[abc]matches one character (a, b, or c),a|b|cmatches complete strings “a”, “b”, or “c”- In text “category”, it would match “cat” instead of “category” because “cat” is tried first
- Use parentheses to group the alternation:
(option1|option2) rest_of_pattern
Practical Challenge
Create a regex pattern that matches any of these greeting formats:
- “Hello, World!”
- “Hi there!”
- “Good morning!”
- “Good afternoon!”
- “Good evening!”
- “Hey!”
Solution:
(Hello, World|Hi there|Good (morning|afternoon|evening)|Hey)!
For Instructors
Teaching Tips
- Show examples where order matters by swapping alternatives in regex101.com
- Use real-world examples of format variations (dates, phone numbers, etc.)
- Demonstrate both successful and problematic alternation patterns
- Emphasize when to use alternation vs. character classes
Assessment Ideas
- Format Matching: “Create a pattern to match both US and European date formats”
- Order Challenge: “Fix this pattern that matches ‘cat’ instead of ‘category’:
cat|category” - Grouping Exercise: “Make this pattern work correctly:
red|blue car”
Adaptation Notes
- For Beginners: Start with simple two-option alternations before complex cases
- For Advanced Users: Discuss performance implications and regex engine optimization
- Online Delivery: Use regex101.com to show live alternation matching behavior
- Time Management: Focus on hands-on practice with real format variations
Common Student Questions
Q: “Can I use alternation inside character classes?”
A: No, [a|b] matches the characters ‘a’, ‘|’, or ‘b’. Use (a|b) for alternation.
Q: “How many alternatives can I have?” A: Technically unlimited, but very long alternations become hard to read and slow to execute. Consider refactoring if you have more than 10-15 alternatives.
Q: “Does alternation work with quantifiers?”
A: Yes! (cat|dog)+ matches “cat”, “dog”, “catcat”, “dogcat”, etc. The quantifier applies to the entire group.
Q: “Why doesn’t my alternation match the longest option?” A: Regex alternation is “first match wins,” not “best match wins.” Put longer alternatives first to ensure they’re tried before shorter ones.