Alternation (OR) |
The pipe | acts as an OR operator, matching either the pattern on the left or the right.
Basic Alternation
Matches either "cat" OR "dog".
Exercises
Alternation with Groups
Without groups, alternation applies to the entire pattern on each side:
This matches "I love cats" OR "dogs" - probably not what you want!
Use groups to limit alternation scope:
Now it matches "I love cats" OR "I love dogs".
Practical Examples
Order Matters
Alternatives are tried left to right. The first match wins:
Since "cat" is first, it matches before "category" can be fully matched.
Now "category" matches fully because it's tried first.
Practice Playground
Try:
http|ftp- protocolsactive|inactive|pending- status values@\w+|email- social or email
Key Takeaways
a|bmatches a OR b- Chain multiple alternatives:
a|b|c|d - Use groups to limit scope:
prefix(a|b|c) - Order matters - first match wins
- Combine with other patterns freely

