Regex Alternation

Summary: in this tutorial, you will learn how to use regex alternation to match one pattern or another.

Introduction to the regex alternation

Regex alternation is like the OR operator in regular expressions, which allows you to match one pattern or another. Regex alternation is denoted by an alteration operator (|):

pattern1 | pattern2 | pattern3Code language: C# (cs)

It is also known as regex OR or regex choice.

When matching a pattern with an alteration, the regex engine will attempt to match each pattern sequentially from left to right. If a regex pattern finds a match, it stops matching immediately and returns the result.

Regex alternations are useful when you want to specify multiple options for a pattern to match.

Regex alternation examples

Let’s explore some examples of using the regex alternation.

1) Using regex alternation to match a specific word

The following example uses the regex alteration to match either apple, banana, or orange word in a text:

using System.Text.RegularExpressions;
using static System.Console;


var text = "apple, banana, orange";
var pattern = @"apple|banana|orange";
var matches = Regex.Matches(text, pattern);

foreach (var match in matches)
{
    WriteLine(match);
}Code language: C# (cs)

It returns three matches:

apple
banana
orangeCode language: C# (cs)

2) Using regex alternation to match a time string in the format hh:mm

The following example uses a regex alternation to match the time string in the format hh:mm in a string:

using System.Text.RegularExpressions;
using static System.Console;


var text = "08:20 50:91 21:45 26:99";
var pattern = @"([01][0-9]|2[0-3]):[0-5][0-9]";

var matches = Regex.Matches(text, pattern);

foreach (var match in matches)
{
    WriteLine(match);
}Code language: C# (cs)

It returns two matches corresponding to the valid time format hh:mm:

08
21:45Code language: C# (cs)

The regular expression pattern [01]\d|2[0-3]:[0-5]\d matches either a two-digit number starting with 0 or 1, or a time in the format hh:mm between 20:00 and 23:59.

Let’s understand the regular expression ([01][0-9]|2[0-3]):[0-5][0-9] step by step:

  • ([01][0-9]|2[0-3]) matches the hour portion of the time format. It contains two alternatives separated by the alternation operator (|). The first alternative [01][0-9] matches hours from 00 to 19, representing the hours from 00 to 19. The second alternative 2[0-3] matches hours from 20 to 23.
  • : matches the colon character, which separates the hour and minute portions of the time format.
  • [0-5][0-9] matches the minute portion of time from 00 to 59.

Summary

  • Use regex alternation (|) to match one pattern or another within the same regular expression.
Was this tutorial helpful ?