Python Workout 07: Regular Expressions 101

Level of difficulty:

Objective: This workout provides practice in utilizing regular expression functions.

Problem: The vertical bar | is the equivalent to “or” in RegEx. The regular expression x | y matches either “x” or “y”. Write the regular expression that will match all red flag and blue flag in a string. You must use | in your expression. Flags can come in any order.

Examples:

txt1 = "red flag blue flag"
txt2 = "yellow flag red flag blue flag green flag"
txt3 = "pink flag red flag black flag blue flag green flag red flag"
pattern = "yourregularexpressionhere"

re.findall(pattern, txt1) ➞ ["red flag", "blue flag"]
re.findall(pattern, txt2) ➞ ["red flag", "blue flag"]
re.findall(pattern, txt3) ➞ ["red flag", "blue flag", "red flag"]

Submission

Simply post your code and a screenshot of your results.

Please format your Python code and blur it or place it in a hidden section.

This workout will be released on Thursday April 20, 2023, and the author’s solution will be posted on Wednesday April 26, 2023.

Nice one Kedeisha

2 Likes

import re

txt1 = “red flag blue flag”
txt2 = “yellow flag red flag blue flag green flag”
txt3 = “pink flag red flag black flag blue flag green flag red flag”
pattern = “red flag|blue flag”

re.findall(pattern, txt1)
re.findall(pattern, txt2)
re.findall(pattern, txt3)

1 Like

Thanks @kedeisha1 for the workout. Here is my solution using jupyter notebook.

Summary

1 Like

My Solution

txt1 = "red flag blue flag"
txt2 = "yellow flag red flag blue flag green flag"
txt3 = "pink flag red flag black flag blue flag green flag red flag"
pattern = "red flag|blue flag"

re.findall(pattern, txt1) ➞ ["red flag", "blue flag"]
re.findall(pattern, txt2) ➞ ["red flag", "blue flag"]
re.findall(pattern, txt3) ➞ ["red flag", "blue flag", "red flag"]