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

Alternation Scope — Where | Reaches

~6 min · alternation, scope, precedence

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

Alternation has the lowest precedence

The | operator binds LOOSER than anything else in regex. Whatever comes before and after the pipe extends as far as it can — usually all the way to the nearest enclosing parentheses (or the start/end of the entire pattern).

So abc|xyz means 'abc' OR 'xyz' — not 'abc followed by either nothing or xyz.'

And a(bc|xy)z means 'a, then either bc or xy, then z.' The parentheses contain the alternation.

Multi-branch alternation

You can chain alternatives: red|green|blue|yellow matches any of the four colors. There's no special syntax — just keep adding pipes.

For more than 5-6 alternatives, consider whether a character class would work, or whether the alternatives have a common shape that could be expressed as a single pattern.

Empty alternatives

A pipe with nothing on one side — foo| or |foo — matches an empty string OR foo. Equivalent to foo? when wrapped: (foo|) matches the same as (foo)?. Some engines accept it, some don't. Don't rely on it.

Code

Alternation scope·python
import re

# Top-level alternation — extends all the way
re.search(r'abc|xyz', 'abcxyz').group()
# 'abc'  — first alternative wins; the whole pattern is 'abc' OR 'xyz'

# Group-bounded alternation
re.findall(r'a(bc|xy)z', 'abcz axyz aXz')
# ['bc', 'xy']

# Multi-branch
re.findall(r'red|green|blue|yellow', 'roses red and violets blue and grass green')
# ['red', 'blue', 'green']

# Common bug: anchor across alternation
re.findall(r'^foo|bar$', 'bar foo')
# ['foo']  — '^foo' OR 'bar$', not '^(foo|bar)$'
# What you probably wanted:
re.findall(r'^(?:foo|bar)$', 'foo')
# ['foo']  — only matches whole-line 'foo' or 'bar'

External links

Exercise

Write a regex matching any of: a line that starts with 'INFO', 'WARN', or 'ERROR' (anchored). Without grouping, your pattern fails on most cases. With grouping, it works. Show both versions.

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.