Fix the Email Validator
Intermediate · Fix the bug · from Python Regular Expressions: Pattern Matching from Basics to Advanced
From the lesson: Python Regular Expressions: Pattern Matching from Basics to Advanced
Imagine you're working at a help desk and need to find every email address buried in thousands of support tickets. You could scan each line character by character, but that would take forever. Regular expressions let you describe the pattern of an email address, and Python finds every match for you.
Read the lessonThis email validator has two bugs. Find and fix them so it correctly validates that a string looks like an email address (one or more word characters/dots/hyphens, then @, then a domain, then a dot, then 2-4 letters).
import re
def is_valid_email(email):
# BUG 1: Missing raw string prefix
# BUG 2: Pattern doesn't anchor to start/end
pattern = '[\w.-]+@[\w.-]+\.\w{2,4}'
match = re.search(pattern, email)
return match is not None
print(is_valid_email('alice@example.com'))
print(is_valid_email('not-an-email'))
print(is_valid_email('!!!bad@email.com!!!'))
More Regex exercises
- Find a Phone NumberIntermediate
- Extract All HashtagsIntermediate
- Predict the Regex OutputIntermediate
- Censor Credit Card NumbersIntermediate
- Parse a Log EntryIntermediate
- Clean and Normalize WhitespaceAdvanced
All Python exercises · 50 practice problems · Standard Library Essentials quiz