Level: Intermediate | Prerequisite: Week 8
Learning Goals
- Use the
remodule for pattern matching - Know commonly used metacharacters (
\d,\w,+,*,?) - Utilize group capturing
- Use replacement (
re.sub)
1. Basic Usage
import re
#Search (First Match)
m = re.search(r"\d{3}-\d{4}-\d{4}", "Phone: 010-1234-5678")
print(m.group()) # 010-1234-5678
#Find All
print(re.findall(r"\d+", "5 apples, 3 bananas")) # ['5', '3']
#Match Status
if re.match(r"^\d+$", "12345"):
print("Numbers Only")
#Replace
print(re.sub(r"\d+", "?", "5 apples, 3 bananas")) #? apples, ? bananas
2. Commonly Used Metacharacters
| Pattern | Meaning |
|---|---|
. |
Any single character |
\d |
Digit ([0-9]) |
\D |
Non-digit |
\w |
Alphanumeric, underscore |
\s |
Whitespace |
^ |
Start |
$ |
End |
[abc] |
One of a, b, c |
[^abc] |
Not a, b, c |
[a-z] |
Range |
3. Quantifiers
| Pattern | Meaning |
|---|---|
* |
0 or more times |
+ |
1 or more times |
? |
0 or 1 time |
{n} |
Exactly n times |
{n,m} |
n to m times |
? (after quantifier) |
Minimum matching (non-greedy) |
4. Group Capturing
Group by (...). Extract by m.group(N) or m.groups().
log = "ERROR 2026-05-09 14:32 Authentication Failed"
m = re.match(r"(\w+) (\d{4}-\d{2}-\d{2}) (\d{2}:\d{2}) (.+)", log)
print(m.groups()) #('ERROR', '2026-05-09', '14:32', 'Authentication Failed')
#Naming Group
m = re.match(r"(?P<level>\w+) (?P<date>\d{4}-\d{2}-\d{2})", log)
print(m.group("level"), m.group("date"))
5. raw string
Prevent escape collisions. Regex always recommend r"...".
#For regular strings, \d should be interpreted as \\d to be safe
re.findall(r"\d+", text) #Recommended
re.findall("\\d+", text) #Same but confusing
6. Compile
If using the same pattern multiple times, pre-compile.
email_re = re.compile(r"[\w.]+@[\w.]+\.\w+")
emails = email_re.findall("Contact: [email protected], [email protected]")
print(emails)
Key Examples (examples/)
| File | Content |
|---|---|
01_basic.py |
search, findall |
02_meta.py |
Meta character |
03_groups.py |
Group capture |
04_sub_compile.py |
sub, compile |
⚠️ Common Mistakes
- Missing escape — Not added inside
r→\d→d. Alwaysr"...". - Greedy matching —
<.+>matches the entire<a><b>. Minimal matching is<.+?>. matchvssearch—matchonly the first time,searchanywhere.- Regex too complex — If readability drops, just branch in code.
❓ FAQ
Q1. How to debug regex? A. Test patterns on sites like https://regex101.com.
Q2. Is regex slow? A. Generally fast. But catastrophic backtracking patterns are very slow.
Q3. Perfect email validation pattern?
A. Exact RFC validation is very long. For practical level, use [\w.+-]+@[\w-]+\.[\w.-]+.
📝 Exercises (exercises/)
exercise1.md— Extract emailsexercise2.md— Validate mobile numbersexercise3.md— Extract only ERROR from logs
Next Week
Week 10. Comprehensive practice