A regular expression (regex) is a pattern that describes text, like “three digits, a dash, four digits.” Python’s built-in re module uses these patterns to find, extract, validate, and replace text: pulling order numbers out of emails, cleaning phone numbers, checking ZIP codes, or counting errors in a log file.
String methods like .replace() and .split() handle exact text. Regular expressions handle text that follows a pattern but varies: every email address in a document, phone numbers written five different ways, dates in a log. They look cryptic at first, but a small set of symbols covers most everyday jobs, and once you know them, you’ll use them in Python, in your code editor’s search, in SQL, and in command-line tools.
This guide teaches the regex syntax you’ll actually use and the re functions that apply it, with practical examples. Every example was run, and the outputs are real.
Always Use Raw Strings
Write patterns as raw strings, with an r before the quotes: r"\d+". Regex uses backslashes a lot, and in a normal string Python would try to interpret them itself (\b, for example, means “backspace” in a normal string but “word boundary” in a regex). Raw strings pass them through untouched.
The Syntax You’ll Use Most
| Pattern | Matches | Example |
|---|---|---|
\d | Any digit | \d\d matches 42 |
\w | A letter, digit, or underscore | \w+ matches hello_2 |
\s | Whitespace (space, tab, new line) | a\sb matches a b |
\D, \W, \S | The opposite of the above | \D matches - |
. | Any character except a new line | a.c matches abc |
[abc] | One of the listed characters | [aeiou] matches a vowel |
[^abc] | Any character not listed | [^0-9] matches a non-digit |
[a-z] | A range | [A-Z] matches a capital letter |
+ | One or more of the previous item | \d+ matches 2026 |
* | Zero or more | ab* matches a, abbb |
? | Optional (zero or one) | colou?r matches both spellings |
{n}, {n,m} | Exactly n, or between n and m | \d{5} matches a ZIP code |
^, $ | Start, end of the text (or line) | ^Error |
\b | A word boundary | \bcat\b doesn’t match catalog |
(...) | A group you can extract | (\d{4}) |
a|b | Either a or b | jpg|png |
To match a special character literally, like a period or a dollar sign, escape it with a backslash: \. or \$.
Find the First Match: re.search()
re.search() scans the text and returns the first match, or None:
import re
message = "Hi, I have a question about order #48213 placed last week."
match = re.search(r"#(\d+)", message)
if match:
print(match.group())
print(match.group(1))
#48213
48213
group() (or group(0)) is the whole match. The parentheses in the pattern create group 1, just the digits. Always check that a match exists before using it; calling .group() on None is a classic AttributeError.
Find Every Match: re.findall()
re.findall() returns a list of all matches:
import re
text = """Contact Ana at [email protected] or (760) 555-0142.
Billing questions: [email protected], 760-555-0199."""
emails = re.findall(r"[\w.+-]+@[\w-]+\.[\w.]+", text)
phones = re.findall(r"\(?\d{3}\)?[\s.-]?\d{3}-\d{4}", text)
print(emails)
print(phones)
['[email protected]', '[email protected]']
['(760) 555-0142', '760-555-0199']
The email pattern means: one or more letters, digits, dots, plus signs, or dashes, then @, then a domain. The phone pattern allows optional parentheses and an optional space, dot, or dash. Real-world email addresses can be more varied than this, so treat a pattern like this as “good enough to extract,” not a perfect validator.
Extract Parts With Groups
When a pattern has several groups, groups() returns them all:
import re
line = "Invoice 2026-11-28 total $1,317.50"
match = re.search(r"(\d{4})-(\d{2})-(\d{2})", line)
year, month, day = match.groups()
print(year, month, day)
2026 11 28
For longer patterns, named groups make the code readable. Write (?P<name>...):
import re
line = "Invoice 2026-11-28 total $1,317.50"
match = re.search(r"(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})", line)
print(match.group("month"))
print(match.groupdict())
11
{'year': '2026', 'month': '11', 'day': '28'}
Replace Text: re.sub()
re.sub(pattern, replacement, text) replaces every match. This normalizes phone numbers written in different styles. First it removes everything that isn’t a digit (\D), then it uses groups and backreferences (\1, \2, \3) to rebuild one consistent format:
import re
raw = ["(760) 555-0142", "760.555.0199", "7605550110", "760 555 0177"]
for number in raw:
digits = re.sub(r"\D", "", number)
print(re.sub(r"(\d{3})(\d{3})(\d{4})", r"(\1) \2-\3", digits))
(760) 555-0142
(760) 555-0199
(760) 555-0110
(760) 555-0177
The same idea hides sensitive data before sharing a document or log, here masking all but the last four digits of card numbers:
import re
note = "Card 4111 1111 1111 1234 was charged; backup card 5500-0000-0000-0004."
print(re.sub(r"\b(?:\d{4}[ -]?){3}(\d{4})\b", r"**** **** **** \1", note))
Card **** **** **** 1234 was charged; backup card **** **** **** 0004.
(?:...) is a group that doesn’t capture anything; it just applies {3} to the whole “four digits plus an optional separator” unit.
Split on Several Separators: re.split()
str.split() takes one separator. re.split() takes a pattern, which handles messy input:
import re
tags = "python, sql; excel |power bi,automation"
print(re.split(r"\s*[,;|]\s*", tags))
['python', 'sql', 'excel', 'power bi', 'automation']
\s*[,;|]\s* means “a comma, semicolon, or pipe, with any spaces around it.”
Validate Input: re.fullmatch()
re.search() finds a pattern anywhere in the text, so \d{5} would happily match inside 92243a. To check that the whole value matches, use re.fullmatch():
import re
def is_zip_code(value):
return re.fullmatch(r"\d{5}(-\d{4})?", value) is not None
for value in ["92243", "92243-1234", "9224", "92243a"]:
print(value, is_zip_code(value))
92243 True
92243-1234 True
9224 False
92243a False
(-\d{4})? makes the ZIP+4 extension optional. For complex formats, like email addresses or dates, prefer a dedicated library or a real parser (datetime.strptime() for dates) over an ever-growing regex.
Flags
Flags change how a pattern matches. re.IGNORECASE ignores capitalization, and re.MULTILINE makes ^ and $ match at the start and end of every line, not just the whole text:
import re
text = "ERROR disk full\nInfo: backup done\nerror: timeout on web01"
print(re.findall(r"^error.*$", text, flags=re.IGNORECASE | re.MULTILINE))
['ERROR disk full', 'error: timeout on web01']
Combine flags with |. For long patterns, re.VERBOSE lets you spread a pattern over several lines with comments, which makes it far easier to read later. re.compile() saves the pattern for reuse:
import re
PHONE = re.compile(r"""
\(?(\d{3})\)? # area code, with optional parentheses
[\s.-]? # optional separator
(\d{3}) # first three digits
[\s.-]? # optional separator
(\d{4}) # last four digits
""", re.VERBOSE)
print(PHONE.findall("Call (760) 555-0142 or 760.555.0199"))
[('760', '555', '0142'), ('760', '555', '0199')]
When a pattern has several groups, findall() returns a tuple of the groups for each match.
Greedy vs. Lazy
By default, * and + are greedy: they match as much as possible. That can surprise you:
import re
html = '<a href="/posts/">Blog</a> and <a href="/contact/">Contact</a>'
print(re.findall(r'href="(.*)"', html))
print(re.findall(r'href="(.*?)"', html))
['/posts/">Blog</a> and <a href="/contact/']
['/posts/', '/contact/']
The greedy .* ran all the way to the last quote on the line. Adding ? (.*?) makes it lazy, matching as little as possible, which gives the two links. (For real HTML, an HTML parser like Beautiful Soup is more reliable; see Web Scraping With Python.)
A Real Example: Analyzing a Web Server Log
Web server logs are a perfect regex job: every line follows the same format. This counts response codes and lists the “page not found” requests, which here reveal someone probing for WordPress login pages:
import re
from collections import Counter
log = """192.168.1.20 - - [28/Nov/2026:10:15:32 -0800] "GET /posts/ HTTP/1.1" 200 5120
192.168.1.21 - - [28/Nov/2026:10:15:40 -0800] "GET /contact/ HTTP/1.1" 200 2048
203.0.113.9 - - [28/Nov/2026:10:16:02 -0800] "GET /wp-login.php HTTP/1.1" 404 512
203.0.113.9 - - [28/Nov/2026:10:16:03 -0800] "POST /xmlrpc.php HTTP/1.1" 404 512
192.168.1.20 - - [28/Nov/2026:10:17:11 -0800] "GET /posts/sql-views-guide/ HTTP/1.1" 200 8192"""
pattern = re.compile(r'^(?P<ip>\S+) .*?"(?P<method>[A-Z]+) (?P<path>\S+) [^"]*" (?P<status>\d{3})', re.MULTILINE)
statuses = Counter()
not_found = Counter()
for m in pattern.finditer(log):
statuses[m["status"]] += 1
if m["status"] == "404":
not_found[(m["ip"], m["path"])] += 1
print(statuses)
for (ip, path), count in not_found.items():
print(f"404 from {ip}: {path}")
Counter({'200': 3, '404': 2})
404 from 203.0.113.9: /wp-login.php
404 from 203.0.113.9: /xmlrpc.php
finditer() returns match objects one at a time, which is memory-friendly for big files, and m["status"] reads a named group. Swap the sample text for open("access.log").read() to analyze a real log. Requests like these are one reason to protect logins, as covered in Cybersecurity Fundamentals.
Common Mistakes to Avoid
- Forgetting the
rprefix. Use raw strings for every pattern. - Using
search()for validation. Usefullmatch()so extra characters don’t slip through. - Not escaping special characters. A
.matches any character; use\.for a real period. - Greedy matches that run too far. Add
?to make*or+lazy. - Calling
.group()onNone. Checkif match:first. - Writing one giant pattern. Break the job into steps, use
re.VERBOSEwith comments, or use a parser when the format is complex (HTML, JSON, CSV, dates).
Quick Reference
| Function | Returns |
|---|---|
re.search(p, text) | The first match object, or None |
re.fullmatch(p, text) | A match only if the whole text matches |
re.findall(p, text) | A list of all matches (or group tuples) |
re.finditer(p, text) | Match objects, one at a time |
re.sub(p, repl, text) | The text with matches replaced |
re.split(p, text) | A list of pieces between matches |
re.compile(p) | A reusable pattern object |
Frequently Asked Questions
Are regular expressions the same in every language?
The core syntax (\d, [a-z], +, groups) is nearly identical in Python, JavaScript, PowerShell, most editors, and many databases. Advanced features and the replacement syntax vary slightly.
How do I test a regex before using it?
Try it in the Python shell with a few sample strings, including ones that should not match. Online regex testers that support Python’s flavor are also handy for seeing what each part matches.
Should I use regex to clean data in pandas?
Yes: pandas string methods like str.replace(), str.extract(), and str.contains() accept regex patterns. See Data Cleaning With Python Pandas.
Conclusion
Regular expressions describe patterns in text, and Python’s re module puts them to work: search() to find, findall() and finditer() to collect, groups to extract parts, sub() to replace, split() to break apart, and fullmatch() to validate. Start with the handful of symbols in the table above, always use raw strings, test with examples that should and shouldn’t match, and keep patterns small and readable. They’ll save you hours of manual text work.
