Module 4 · Lesson 2 of 414/32 in the course~16 min
Module lessons (2/4)
Alternation: `|`
Lesson preview5 hands-on exercises readyRegex Course · Module 4 — Groups and alternation
The pipe chooses between two or more sub-patterns; precedence and parentheses.
What you'll learn in this lesson
- Choose between multiple alternative branches using the pipe operator
|("logical OR"). - Understand the very low precedence of the pipe and always delimit the OR with brackets
(...)or(?:...). - Correctly order the alternatives when one is a prefix of the other (e.g.
httpsbeforehttp,gattobeforegat). - Prefer a character class (
[abc]) to a pipe (a|b|c) for faster and clearer single character choices.
Overview
The pipe | performs logical OR in regular expressions: the pattern succeeds if at least one of the branches separated by | matches. However, it has the lowest syntactic precedence of all the regex syntax: without brackets it involves everything that precedes up to the beginning of the line/group and everything that follows up to the…
Sections covered in this lesson
- 1Mental model: precedence and order of alternatives
- 2Progressive examples
- 3Guided laboratory
- 4Check for understanding
Pro Lesson · Module 4 — Groups and alternation
Unlock "Alternation: `|`" and the full Regex Course curriculum
The pipe chooses between two or more sub-patterns; precedence and parentheses.
Unlock all 5 hands-on exercises in this lesson plus every advanced WebAssembly module with automated checks.
- Instant access to all advanced modules in Regex Course plus 17 more courses
- Hands-on browser exercises with automated test suites and solutions
- 14-day money-back guarantee processed via Paddle.com
14-day guarantee · Cancel anytimeModule 1, all 18 interactive games, and cheatsheets are always free.