Alternation
The | operator chooses between alternatives. Why it binds loosest, why JavaScript takes the first alternative that works, and how POSIX tools differ.
Quantifiers: star, plus and questionAnchors and line boundaries
Alternation
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- a|b matches a or b. The whole text on one side of | is one alternative, so cat|dog means the three letters cat or the three letters dog.
- In backtracking engines (JavaScript, Python, Perl, PCRE) the first alternative that lets the whole pattern succeed wins, not the longest. /Java|JavaScript/ matches only Java in JavaScript.
- Put longer or more specific alternatives first, or anchor with \b. /JavaScript|Java/ finds JavaScript, and \d{4}|\d{1,3} reads 2026 whole where \d{1,3}|\d{4} stops at 202.
- macOS grep -E and sed -E chose the longest alternative, JavaScript, for Java|JavaScript. That looks like POSIX leftmost-longest matching, and it differs from JavaScript.
- An empty alternative is allowed and matches nothing, so /cat|dog|/ matches every string. Watch for a stray trailing or doubled |.
Either this or that
A character class chooses between single characters. What about whole words? You want any line that mentions cat or dog. [cd] is no help, because the choice is between three-letter words. For this the operator is |, read as “or”:
"I have a cat and a dog".match(/cat|dog/g) // [ 'cat', 'dog' ]
"cats dog dogs".match(/(?:cat|dog)s?/g) // [ 'cats', 'dog', 'dogs' ]
Everything to the left of the bar, up to the pattern’s start or the nearest enclosing parenthesis, is one alternative. Everything to the right, up to the end or the next bar, is another. cat|dog is not ca(t|d)og. It means the whole word cat or the whole word dog. The second line wraps the choice in a group, so the s? applies to whichever alternative matched.
For single characters, a class is the shorter spelling. "gray grey".match(/gr(?:a|e)y/g) and /gr[ae]y/g both returned ['gray', 'grey'], and the class is easier to read. Use | when the choices are longer than one character.
Lowest precedence
| binds more loosely than anything else in the pattern. That is easy to misread when anchors are involved:
["cat","dogs","catfish","a dog"].map(s => /^cat|dog$/.test(s)) // [ true, false, true, true ]
["cat","dogs","catfish","a dog"].map(s => /^(?:cat|dog)$/.test(s)) // [ true, false, false, false ]
The first pattern is ^cat or dog$. So catfish matches (it starts with cat) and a dog matches (it ends with dog). The second pattern puts the choice in a group so both anchors apply to either word, and only cat passes. The same thing happens in grep -E: '^cat|dog$' printed cat, catfish and a dog, while '^(cat|dog)$' printed only cat. The next lesson lays out the full order.
First match wins
Now the part that surprises people. Given Java|JavaScript on the text JavaScript, which does it return?
"JavaScript".match(/Java|JavaScript/)[0] // "Java"
"JavaScript".match(/JavaScript|Java/)[0] // "JavaScript"
In JavaScript, Python and Perl and PCRE alike, the engine tries the alternatives in the order you wrote them. It commits to the first one that lets the whole pattern succeed. Java fits at position 0, nothing after it needs to match, so the engine stops there. It has no urge to look for a longer match. The choice is ordered, and the left alternative has priority.
Python gave Java and JavaScript for the two orders, perl gave Java, and pcre2grep -o gave Java. The numbers are the same story:
"2026".match(/\d{1,3}|\d{4}/)[0] // "202"
"2026".match(/\d{4}|\d{1,3}/)[0] // "2026"
When you write alternatives where one is a prefix of another, put the longer one first, or fence the group with \b so that only a whole word counts: "JavaScript".match(/\b(?:Java|JavaScript)\b/)[0] returned JavaScript, because Java followed by S is not a word boundary, so the engine went back and tried the next alternative.
That last point is the engine’s safety net: it will try later alternatives if a choice leads to failure later in the pattern. (?:a|ab)c found abc in "abc": it tried a, c didn’t follow, so it came back and tried ab.
The leftmost start still beats an earlier alternative. /b|abc/ on "abc" matched abc at index 0, because position 0 is tried before position 1, and at position 0 the first alternative b fails and the second succeeds.
POSIX picks the longest
The command-line tools may follow a different rule. On macOS, with BSD tools:
$ echo JavaScript | /usr/bin/grep -oE 'Java|JavaScript'
JavaScript
$ echo JavaScript | sed -E 's/Java|JavaScript/X/'
X
grep printed the whole word and sed replaced the whole word, so both took the longest alternative, no matter the order. The same substitution in Perl and in JavaScript printed XScript. This is called leftmost-longest matching, and I believe it comes from the POSIX standard, but I only observed it on macOS. Code that depends on order will behave differently in the two families, so order your alternatives longest-first and you get the same answer in both.
Basic syntax spells the bar \|: grep -o 'cat\|dog' and grep -oE 'cat|dog' both printed cat and dog, while plain grep -o 'cat|dog' on cat|dog matched the literal text.
The empty alternative
A branch can be empty, and an empty branch matches the empty string, which fits at every position:
/cat|dog|/.test("zzz") // true
/^(cat|dog|)$/.test("") // true
/^(cat|dog)$/.test("") // false
Deliberately, (cat|dog|) is a way to say “optional”. By accident, a doubled || or a trailing | turns a precise pattern into one that matches everything. It is a common cause of “my filter lets everything through”.
About the video
The embed is a clip of Kris Jordan’s “Regular Expression OR Operator and Operator Precedence (aka the Alternation Operator)”, published on 17 May 2020 and 11 minutes 53 seconds long. The clip plays from the start to 4:43 and covers the chapters “The case of the bank robbery”, “Introduction to OR operator”, “Practical OR operator examples” and the opening of “Operator precedence in regex”. The rest of the video is used in the next lesson. The description says the OR operator has lower precedence than the “and then” operator and that parentheses control the order. It is the second video in his short course, which uses VS Code and puzzle files. I couldn’t read a transcript, so I can’t say whether it covers ordered choice or POSIX differences, and I suspect it does not. English per its title and description.
What I did not run
GNU grep and sed, regex101, and a strict POSIX implementation. The leftmost-longest rule is only what I saw on macOS.
Next
You’ve now met three operators with different strengths: concatenation, quantifiers and the bar. The last lesson in this group puts them in order and builds a pattern piece by piece: How a pattern is read: precedence and grouping.
Check yourself
What does /Java|JavaScript/ match in the string 'JavaScript', and what would change in grep -E?
JavaScript's engine returns Java, because the first alternative succeeds. macOS grep -E returned JavaScript, the longest match. Reorder to JavaScript|Java to be safe in both.
Why does /^cat|dog$/ match 'catfish' and 'a dog'?
| splits the whole pattern into ^cat and dog$. The anchors apply to one alternative each. Write /^(?:cat|dog)$/ to anchor both.
What does /cat|dog|/.test('zzz') return, and why?
true. The trailing | adds an empty alternative, which matches the empty string at any position.
Why is gr[ae]y usually better than gr(?:a|e)y?
For single characters the class is shorter and does the same job. Use alternation when the choices are longer than one character.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.