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
EasyWrite 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 hereAll lessons in RegEx in Python
1Introduction
Introduction