Find a Phone Number
Intermediate · Write the code · 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 lessonWrite a function find_phone(text) that uses re.search() to find the first phone number in the format XXX-XXX-XXXX in the given text. Return the phone number as a string, or "Not found" if no phone number exists.
import re
def find_phone(text):
# Use re.search() with a pattern for XXX-XXX-XXXX
pass
# Test it
print(find_phone('Call us at 555-867-5309 today!'))
print(find_phone('No number here'))
More Regex exercises
- Extract All HashtagsIntermediate
- Predict the Regex OutputIntermediate
- Censor Credit Card NumbersIntermediate
- Fix the Email ValidatorIntermediate
- Parse a Log EntryIntermediate
- Clean and Normalize WhitespaceAdvanced
All Python exercises · 50 practice problems · Standard Library Essentials quiz