Alternation
The vertical bar | means or. cat|dog matches either cat or dog. It is the regex equivalent of "one of these alternatives".
/cat|dog|bird/g
I have a dog, two cats and no bird.3 matches
#1 "dog" at index 9
#2 "cat" at index 18
#3 "bird" at index 30
| has the lowest priority
Alternation splits the whole pattern (or the whole group it's in) into alternatives. ^cat|dog$ does not mean "the whole string is cat or dog" — it means "^cat" or "dog$":
/^cat|dog$/g
cat food for my dog2 matches
#1 "cat" at index 0
#2 "dog" at index 16
Use a group to limit the alternation to one part of the pattern:
| Pattern | Meaning |
|---|---|
^cat|dog$ |
starts with cat, or ends with dog |
^(cat|dog)$ |
is exactly cat or exactly dog |
gr(a|e)y |
gray or grey |
(Mon|Tues|Wednes)day |
Monday, Tuesday, Wednesday |
/\b(?:Mon|Tues|Wednes)day\b/g
Monday, Tuesday, Wednesday and Sunday3 matches
#1 "Monday" at index 0
#2 "Tuesday" at index 8
#3 "Wednesday" at index 17
Order matters: first alternative wins
JavaScript (like Python, Java, .NET, PCRE and Ruby) tries alternatives left to right and takes the first one that leads to an overall match — not the longest one.
/Java|JavaScript/g
I write JavaScript and Java.2 matches
#1 "Java" at index 8
#2 "Java" at index 23
Java succeeded first, so the engine never tried JavaScript. Two fixes:
- Put the longer alternative first:
JavaScript|Java. - Or add a boundary so the short one fails inside the long word:
\b(?:Java|JavaScript)\b.
/JavaScript|Java/g
I write JavaScript and Java.2 matches
#1 "JavaScript" at index 8
#2 "Java" at index 23
Note: POSIX tools such as
grep -Eandawkuse the opposite rule — the longest overall match wins. That's one of the flavour differences covered at the end of the course.
Alternation vs character class
When every alternative is a single character, a class is simpler and faster:
| Instead of | Write |
|---|---|
a|e|i|o|u |
[aeiou] |
0|1|2|3|4|5 |
[0-5] |
(\s|,) |
[\s,] |
Keep | for alternatives that are longer than one character.
Empty alternatives
An alternative may be empty: colou(r|) matches the same strings as colou?r, but the ? form is clearer. Avoid empty alternatives — they are easy to create by accident with a trailing |, and an empty alternative matches the empty string at every position.
In code
const extensions = /\.(?:jpe?g|png|gif|webp)$/i;
for (const f of ["photo.JPG", "logo.png", "notes.txt", "anim.gif.zip"]) {
console.log(f, extensions.test(f));
}photo.JPG true
logo.png true
notes.txt false
anim.gif.zip false
Test yourself
What does /^yes|no$/ match?
- Exactly
yesor exactlyno - Text that starts with
yesor ends withno yesfollowed byno- Only
yesno
In JavaScript, what does /in|inside/ match first in inside?
insidein- Nothing
- Both at once
Which is the best way to write x|y|z?
(x)(y)(z)[xyz]x?y?z?[x|y|z]