Regular expressions, commonly known as regex, are powerful tools used in Python and many other programming languages to search, match, and manipulate text based on specific patterns. Whether you're validating user input, parsing logs, or scraping data, understanding common regex patterns will significantly boost your productivity and precision.
In this lesson, we'll explore the most frequently used regex patterns, explain their components in simple terms, and provide practical Python examples so you can confidently apply them in your projects.
Why Learn Common Regex Patterns?
Regex can look intimidating at first — strings of symbols and characters that seem cryptic. However, many patterns repeat across different tasks. By mastering these common patterns, you’ll develop a toolkit that you can adapt to almost any text processing challenge.
💡 Regex is like a Swiss Army Knife for text processing
Think of regex as a multi-tool that lets you dissect and extract information from text quickly. Once you know the right pattern, you can isolate emails, phone numbers, dates, URLs, and much more with ease.
Regex Basics Recap
Before diving into patterns, a quick reminder of some essential regex syntax:
.— Matches any single character except newline\d— Matches any digit (equivalent to [0-9])\w— Matches any alphanumeric character plus underscore (equivalent to [a-zA-Z0-9_])\s— Matches any whitespace character (spaces, tabs, newlines)+— Matches 1 or more repetitions of the preceding element*— Matches 0 or more repetitions?— Makes the preceding element optional (0 or 1 times)[]— Defines a character class; matches any one character inside^and$— Match the start and end of a string respectively
Now, let's see how these building blocks combine into useful patterns.
Common Regex Patterns You Should Know
| Pattern | Purpose |
|---|---|
\d{3}-\d{2}-\d{4} | Matches a Social Security Number format (e.g., 123-45-6789) |
[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+ | Matches an email address |
\b\d{5}(?:-\d{4})?\b | Matches US ZIP codes, optionally with 4-digit extension |
https?://(?:www\.)?\S+ | Matches HTTP or HTTPS URLs |
\(\d{3}\) \d{3}-\d{4} | Matches US phone numbers like (123) 456-7890 |
1. Matching Digits and Numbers
Digits often appear in data, so you will need patterns that match specific numeric formats.
Example: To match exactly 3 digits, you use \d{3}. The curly braces specify the exact count of repetitions.
📌 Deep Dive: Matching a 3-digit number
import re
text = "My code is 123, not 45 or 6789."
pattern = r"\b\d{3}\b" # Matches exactly 3-digit numbers
matches = re.findall(pattern, text)
print(matches)
Here, \b is a word boundary anchor to ensure it matches full numbers, not digits inside longer numbers.
2. Email Addresses
Matching email addresses is a classic regex use case. While email formats can get complicated, a practical pattern that works in many cases is:
[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+
This breaks down as:
[a-zA-Z0-9_.+-]+: One or more allowed characters before the @@: The at symbol[a-zA-Z0-9-]+: Domain name with letters, digits, or hyphens\.: Literal dot[a-zA-Z0-9-.]+: Domain extension (e.g., .com, .co.uk)
📌 Deep Dive: Extracting emails from text
import re
text = "Contact us at support@example.com or sales@example.co.uk."
pattern = r"[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+"
emails = re.findall(pattern, text)
print(emails)
3. Phone Numbers
US phone numbers often appear in the format (123) 456-7890. Here's a regex pattern to match it:
\(\d{3}\) \d{3}-\d{4}
Explanation:
\(and\): Literal parentheses around area code\d{3}: Three digits (area code and prefix): Space\d{4}: Last four digits
📌 Deep Dive: Finding US phone numbers
import re
text = "Call me at (415) 555-1234 or (212) 555-5678."
pattern = r"\(\d{3}\) \d{3}-\d{4}"
phones = re.findall(pattern, text)
print(phones)
4. URLs
URLs are everywhere on the internet, and regex can help you extract them. A simple pattern to match HTTP and HTTPS URLs is:
https?://(?:www\.)?\S+
This means:
https?: Matches 'http' or 'https' (the 's?' means optional 's')://: Literal characters(?:www\.)?: Optional non-capturing group for 'www.'\S+: One or more non-whitespace characters (the rest of the URL)
📌 Deep Dive: Extracting URLs from text
import re
text = "Visit https://www.example.com or http://example.org for info."
pattern = r"https?://(?:www\.)?\S+"
urls = re.findall(pattern, text)
print(urls)
5. ZIP Codes
US ZIP codes can be 5 digits, sometimes followed by a dash and 4 more digits. The regex pattern:
\b\d{5}(?:-\d{4})?\b
Details:
\b: Word boundary\d{5}: Exactly 5 digits(?:-\d{4})?: Non-capturing group matching optional dash plus 4 digits
📌 Deep Dive: Matching ZIP codes
import re
text = "Send mail to 12345 or 12345-6789."
pattern = r"\b\d{5}(?:-\d{4})?\b"
zips = re.findall(pattern, text)
print(zips)

Combining Patterns and Flags
You can combine multiple regex patterns using the pipe | character, which acts as a logical OR. For example, to match either a phone number or an email, you can write:
pattern = r"\(\d{3}\) \d{3}-\d{4}|[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+"
Regex flags modify behavior, such as case-insensitivity re.I or multiline mode re.M. You pass them as an optional argument to functions like re.findall() or re.search().
📌 Deep Dive: Case-insensitive search for domain names
import re
text = "Contact: USER@Example.COM"
pattern = r"[a-z0-9_.+-]+@[a-z0-9-]+\.[a-z0-9-.]+"
email = re.search(pattern, text, re.I)
print(email.group() if email else "No match")
Tips for Writing and Testing Regex
- Use raw strings: Always prefix regex patterns with
r""to avoid escaping backslashes twice. - Test incrementally: Build your regex piece by piece and test frequently.
- Use online testers: Tools like regex101.com provide instant feedback and explanations.
- Document patterns: Write comments or notes explaining complex regex for future you or teammates.
⚠️ Beware of Overly Complex Regex
While regex is powerful, overly complex patterns can become hard to read and maintain. For very complicated parsing, consider combining regex with Python string methods or specialized libraries.
Summary
Regex is an essential skill for any developer working with text data. By learning these common patterns, you can quickly identify and extract emails, phone numbers, URLs, ZIP codes, and more. Combining simple regex elements and using Python's re module unlocks powerful text processing capabilities.
Practice is key! Try writing your own regex patterns for different formats and test them with Python. Soon, regex will become an intuitive part of your programming toolkit.
Quick Knowledge Check
Test what you just learned
Question 1 of 2
Which regex pattern would correctly match an email address?
Question 2 of 2
What does the regex \d{5}(?:-\d{4})? match?
Loading results...