Mark As Completed Discussion

Alternation

In regular expressions, the alternation operator allows you to match one of several patterns. It is denoted by the vertical bar | and acts like an OR operation.

For example, let's say you have a list of fruit names and you want to check if each fruit is either an apple, banana, or orange. You can use the alternation operator to specify multiple patterns:

PYTHON
1import re
2
3# Example: Matching fruit names
4
5fruits = ['apple', 'banana', 'orange', 'strawberry', 'pear']
6
7# Pattern using alternation
8pattern = r'apple|banana|orange'
9
10# Find matches
11for fruit in fruits:
12    if re.search(pattern, fruit):
13        print(fruit, 'is a match')
14    else:
15        print(fruit, 'is not a match')

In this example, the regular expression pattern 'apple|banana|orange' matches any string that is either 'apple', 'banana', or 'orange'. The re.search() function is used to find matches within each fruit name, and the result is printed accordingly.

The alternation operator is a powerful tool in regular expressions as it allows you to specify multiple patterns that can be matched against a given input. You can use it to create flexible and versatile patterns for various matching scenarios.

PYTHON
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment