Python Tutorial 32
Python Tutorial 32
In this video I finish my Regular Expressions coverage. We’ll look at Or, Group, Named Groups,
More Match Object Functions and then we’ll solve some problems.
# ? : Match 0 or 1
# \n : Newline
# boundary
# re.findall(r"\w+(?=\b)", randStr)
# period and space, but only return the word that follows
# re.findall(r"(?<=\d.\s)\w+", randStr)
# a $ in front of them
# re.findall(r"(?<!\$)\d+", randStr)
Or Conditional
regex = re.compile(r"\d\.\s(Dog|Cat)")
print(len(matches))
for i in matches:
print(i)
Create a regex that will match for 5 digit zip codes or zip codes with 5 digits a dash and
Solution
regex = re.compile(r"(\d{5}-\d{4}|\d{5}\s)")
print(len(matches))
for i in matches:
print(i)
Group
Named Groups
regex = r"^(?P<month>\w+)\s(?P<day>\d+)\s(?P<year>\d+)"
Find all of the following real email addresses in this sample data.
Solution
regex = re.compile(r"[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+")
print(len(matches))
for i in matches:
print(i)
For your final Python / Regex problem I want you to match all of the following phone numbers
and then print them.
Solution
print(len(matches))
for i in matches:
print(i[0].lstrip())
Thank you for taking this Regex journey with me. I hope that I was able to show you how
powerful Regular Expressions can be, while at the same time making them easy to understand
and grasp.
In the next part of my tutorial I’ll show you how to work with databases using Python.