Regex Alternation (OR) – A Complete Guide

What is regex alternation?

In regular expressions, the alternation character (|) is used to match one expression OR another. One can use it by placing the alternation character between two possible expressions (a|b). Alternation can be global across the entire expression, or local when enclosed in parentheses.

For example, the following expression will match either abcEdit with Regexity or 123Edit with Regexity:

/abc|123/Edit with Regexity

Alternation Character

The character used for alternation in regex is the pipe character |Edit with Regexity, also known as the vertical bar. It can be typed by holding down shift and pressing the backspace key on the keyboard, often found close to the Enter key on the right-hand side of a qwerty keyboard.

How It Works

Alternation in regex is very simple to understand. Simply place one possible expression (e.g. aEdit with Regexity) before the alternation character and another one (e.g. bEdit with Regexity) after it. The regex engine will match allow matching to progress if one of the expressions can be matched.

/a|b/Edit with Regexity

Alternation can also be chained one after the other to provide more than two possible matches. Simply add more alternation characters as needed:

/a|b|c/Edit with Regexity
/a|b|c|d|e|f/Edit with Regexity

Scope of Alternation Variable

Alternation characters can be scoped (restricting their range) by enclosing them in parenthesis. If an alternation character is encountered within a set of parentheses, it will match only the expressions within the set of parentheses and ignore the rest of the expression.

For example, the following expression will match either catEdit with Regexity or cotEdit with Regexity. The cEdit with Regexity and tEdit with Regexity are matched literally while the aEdit with Regexity and oEdit with Regexity are matched alternatively:

/c(a|o)t/Edit with Regexity

Alternation scoping works in all constructs that make use of parentheses, e.g. capture groups ()Edit with Regexity, non-capture groups (?:)Edit with Regexity, named groups (?<name>…)Edit with Regexity, and lookarounds (?=)Edit with Regexity.

For example, alternations are scoped to the sets of parentheses in the following expressions:

/a(?:1|2|3)/Edit with Regexity
/m(?k<mygroup>a|o|y)th/Edit with Regexity

If the alternation character is not enclosed in parentheses, it is scoped to the entire expression. Possible expressions are extracted from the start of the expression to the end.

Benjamin

Founder, owner, and sole content creator on RegexLand. Enjoys programming, blogging, and teaching others how to do the same. Read more...

Leave a Comment