Learn Regex the Easy Way, Part 6: Alternation and Grouping
Quick Recap
In Part 5, we covered metacharacters, escaping with backslash, and the dot wildcard. We learned the 14 special characters and how to match them literally. Now let’s combine patterns with “or” logic and control what our quantifiers apply to.
The Pipe Means OR
The pipe character | means “or” in regex. cat|dog matches either “cat” or “dog.”
Grouping with Parentheses
Here’s where it gets critical. Without parentheses, the pipe applies to everything on each side:
cat|dog food Matches "cat" OR "dog food"
NOT "cat food" or "dog food"
With parentheses, you limit the scope:
(cat|dog) Either "cat" or "dog"
[[:blank:]] A space
food Literal "food"
Compact: (cat|dog) food
MATCH THESE
cat fooddog foodDO NOT MATCH THESE
bird foodcatdogfood
Multiple Alternatives
You can have as many alternatives as you need: (red|green|b...