Alternation
Lesson 19 of 28 in Coddy's RegEx in Python course.
You can combine alternation with other regex patterns to create more complex expressions. This allows you to match different patterns in different contexts.
import re
text = "The quick brown fox jumps over the lazy dog. The quick blue cat sleeps."
pattern = r"quick (brown|blue)"
matches = re.findall(pattern, text)
print(matches) # Output: ['brown', 'blue']In the above example, the pattern quick (brown|blue) matches the word "quick" followed by either "brown" or "blue".
Challenge
EasyWrite a function named find_pet_names that takes a text string as input and returns a list of pet names that are either "dog", "cat", or "fish" followed by a color (black, white, red).
Try it yourself
import re
def find_pet_names(text):
# Write code hereAll lessons in RegEx in Python
1Introduction
Introduction