Regex Alternation

Created with Sketch.

Regex Alternation

Summary: in this tutorial, you’ll learn about regex alternation, which is simply an “OR” operator in the regular expression.

Introduction to the regex alternation

Regular expressions use the pipe character (|) to denote an alternation. The alternation is simple the OR operator in the regular expressions.

For example, the following pattern uses the alternation (|) to match apple or orange:

'/apple|orange/'

Code language: PHP (php)

Here’s the code:

<?php

$str = "apple, orange, banana";
$pattern = '/apple|orange/';

if (preg_match_all($pattern, $str, $matches)) {
print_r($matches[0]);
}

Code language: PHP (php)

Output:

Array
(
[0] => apple
[1] => orange
)

Code language: PHP (php)

Use the regex alternation for matching time in hh:mm format

To match a time in hh:mm, you can use the following regular expression:

'/\d{2}:\d{2}/'

Code language: PHP (php)

However, the\d{2} pattern also matches 99, which is not a valid hour or minute.

To fix this, you can use the regex alternation. The valid hour ranges from 01 to 23. Therefore, the pattern for matching the hour is as follows:

[01]\d|2[0-3]

Code language: PHP (php)

The minute ranges from 00 to 59. So the pattern for the minute is:

[0-5]\d

Code language: PHP (php)

Here’s the regular expression that matches the time in the hh:mm format:

'/[01]\d|2[0-3]:[0-5]\d/'

Code language: PHP (php)

Also, you can add the capturing groups for both hour and minute:

'/([01]\d|2[0-3]):([0-5]\d)/'

Code language: PHP (php)

The following example illustrates how to use the regex alternation to match the time:

<?php

$times = ['10:20', '24:10', '01:20', '22:99'];
$pattern = '/([01]\d|2[0-3]):([0-5]\d)/';

foreach ($times as $time) {
if (preg_match($pattern, $time, $matches)) {
echo $matches[0] . PHP_EOL;
}
}

Code language: PHP (php)

Output:

10:20
01:20

Code language: PHP (php)

Summary

  • The regex alternation is an OR operator in regular expressions.

Leave a Reply

Your email address will not be published. Required fields are marked *