C.W.K.
Stream
Lesson 05 of 12 · published

Alternation — The | Operator

~8 min · alternation, or

Level 0Pattern-Curious
0 XP0/90 lessons0/15 achievements
0/100 XP to next level100 XP to go0% complete

Match this OR that

The pipe character | means OR. cat|dog matches either the substring 'cat' or the substring 'dog'. The engine tries each alternative left to right; first match wins.

Order matters

Most regex engines are not longest-match — they're first-match. Pattern cat|cats against 'cats' matches just 'cat' because that's tried first. To match the longer one, put it first: cats|cat.

This is the opposite of awk's POSIX longest-match behavior. Most engines you'll use (Python, JS, PCRE) follow first-match.

Always group your alternation

Without parentheses, alternation extends as far as it can in both directions. Pattern cat|dog alone is fine. But pattern my cat|dog means "my cat" OR "dog" — not "my (cat or dog)." To get the latter, wrap: my (?:cat|dog).

This is the #1 alternation bug in beginner regex.

Performance: alternation is expensive

The engine tries every alternative against every position. For long lists, character classes are dramatically faster: [abcde] beats (?:a|b|c|d|e). Use alternation for multi-character alternatives that don't fit in a class.

Code

Alternation patterns·python
import re

# Simple OR
re.findall(r'cat|dog', 'I have a cat and a dog')
# ['cat', 'dog']

# First-match wins — gotcha
re.search(r'cat|cats', 'cats').group()
# 'cat'  — not 'cats'!
re.search(r'cats|cat', 'cats').group()
# 'cats'  — order matters

# Bug: alternation eats more than you think
re.findall(r'my cat|dog', 'my cat my dog')
# ['my cat', 'dog']  — second is just 'dog' (no 'my')

# Fix: group the alternation
re.findall(r'my (?:cat|dog)', 'my cat my dog')
# ['my cat', 'my dog']

# Character class beats short alternation
# These do the same thing
re.findall(r'[aeiou]', 'hello')      # ['e', 'o']
re.findall(r'a|e|i|o|u', 'hello')    # ['e', 'o']  — slower, noisier

External links

Exercise

Write a pattern that matches any of these greetings at the start of a line: 'hi', 'hello', 'hey', 'hola'. Order matters? Try matching 'hello there' — does your pattern get 'hello' or 'hi'? Adjust the order if needed.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.