Python Lesson 28: The Phone Number Pattern That Breaks match()
๐ Full written solution: https://interview-kit-fe.vercel.app/python-lesson-28-regular-expressions ๐ป Code on GitHub: https://github.com/timepasshub2539-hue/leetcode-python/tree/main/python-lesson-28-regular-expressions Chapters: 0:00 The Brittle String Match 0:12 Fun with Learning Technology 0:34 Three Symbols, Zero Memorizing 0:51 What Regex Actually Is 1:00 re.search vs re.match 1:16 Proving the Difference 1:37 Building the Phone Pattern 1:59 Groups: Pulling Out The Pieces 2:12 Named Groups for Readability 2:30 re.sub: Search's Twin 2:44 Redacting a Document 2:59 The Payoff: One Tool, Three Jobs 3:13 An Honest Opinion 3:38 Recap: Four Tools, One Language Learn Python's re module by building a real phone-number pattern from scratch, not by memorizing symbols. See exactly why re.search() and re.match() give different results on the same string, pull data out with groups and named groups, and use re.sub() to redact a document in one line. Ends with a clear opinion on when regex is the right tool and when it isn't. #python #regex #pythontutorial #coding #learntocode Watch next: - The Problem: Length of Longest Subarray With at Most K Frequency #shorts: https://youtu.be/wJhY8bNTjjE - Length of Longest Subarray With at Most K Frequency: https://youtu.be/1A9kGJZp-p4 - How to See Previous Rows WITHOUT Grouping #shorts: https://youtu.be/j-gfB9Gh3ns
You've hit your monthly spend limit ยท raise it at claude.ai/settings/usage?from=cc_cli_limit_message
The solution
import re
pattern = r"(?P<area>\d{3})[-.\s]?(?P<exch>\d{3})[-.\s]?(?P<line>\d{4})"
user_input = "(555) 123-4567"
if m := re.search(pattern, user_input):
print("valid, area code:", m.group('area'))
else:
print("not a phone number")Ready to try it yourself? Solve Python problems with instant feedback in the practice sandbox.
Practice now โ


