Menu
Coddy logo textTech

Pipe Operator

Lesson 18 of 28 in Coddy's RegEx in Python course.

The pipe | operator is used for alternation in regex, meaning it allows you to match one pattern or another. It works like a logical OR operator.

import re

text = "cat dog bird fish"
pattern = r"cat|dog|fish"
matches = re.findall(pattern, text)

print(matches)  # Output: ['cat', 'dog', 'fish']

In the above example, the pattern cat|dog|fish matches any of the words "cat", "dog", or "fish" in the string text.

challenge icon

Challenge

Easy

Write a function named find_fruits_or_colors that takes a text string as input and returns a list of words that are either fruits (apple, banana) or colors (red, blue).

Try it yourself

import re

def find_fruits_or_colors(text):
    # Write code here

All lessons in RegEx in Python