🧠 Python re Module — Summary
🔧 Commonly Used Methods:
| Method | Description | Example |
|---|
re.search() | Finds the first match anywhere in the string | re.search(r'\d+', 'abc123') → '123' |
re.match() | Matches a pattern only at the beginning | re.match(r'\d+', '123abc') → '123' |
re.findall() | Returns all non-overlapping matches as a list | re.findall(r'\d+', 'a1b22') → ['1', '22'] |
re.sub() | Replaces matched substrings | re.sub(r'\d+', '*', 'abc123') → 'abc*' |
re.split() | Splits string based on regex pattern | re.split(r'[\s,]+', 'a, b c') → ['a', 'b', 'c'] |
Use r'...' to write regex in Python so that backslashes like \s are treated literally, not as Python escape characters. ✅
📘 Regex Pattern Cheatsheet:
| Pattern | Meaning | Example Match |
|---|
\d | Digit (0–9) | '1', '5' |
\D | Non-digit | 'a', '#' |
\w | Word character (a-z, A-Z, 0–9, _) | 'a', 'Z', '7' |
\W | Non-word character | '@', ' ' |
\s | Whitespace (space, tab, newline) | ' ', '\n', '\t' |
\S | Non-whitespace | 'a', '1', '.' |
. | Any character (except newline) | 'a', '5', '!' |
* | 0 or more times | 'a*' → '', 'aaa' |
+ | 1 or more times | 'a+' → 'a', 'aa' |
{m,n} | Between m and n times | 'a{2,4}' → 'aa' |
| ` | ` | OR |
() | Grouping | (\d+)-(\w+) |
[] | Character set | [a-z], [0-9] |
✅ Examples we've used:
command = "G()(al)"
1. Replace () with "o" and (al) with "al":
re.sub(r'\(\)', 'o', re.sub(r'\(al\)', 'al', command))
re.findall(r'\d+', 'I have 2 apples and 10 bananas')
3. Replace multiple spaces with one:
re.sub(r'\s+', ' ', 'This is ChatGPT')
4. Split by space, comma, or semicolon:
re.split(r'[,\s;]+', 'apple, banana; orange')
🧪 Example 1: Check if a string is a valid email
import re
email = "test123@example.com"
if re.match(r'^[\w\.-]+@[\w\.-]+\.\w+$', email):
print("✅ Valid email")
else:
print("❌ Invalid email")
text = "Alice and Bob went to NewYork"
capital_words = re.findall(r'\b[A-Z][a-z]*\b', text)
print(capital_words)
🧪 Example 3: Replace all digits with #
text = "My phone number is 010-1234-5678"
masked = re.sub(r'\d', '#', text)
print(masked)
text = "Today is great! #sunny #happy #blessed"
hashtags = re.findall(r'#\w+', text)
print(hashtags)
html = "<div>Hello <b>world</b></div>"
cleaned = re.sub(r'<.*?>', '', html)
print(cleaned)