Category
|
Pattern
|
Replacement
|
Example (Before)
|
Example (After)
|
Basic Syntax
|
re.sub(pattern, replacement, string)
|
Replaces all occurrences
|
'Phone: 123-456-7890'
|
'Phone: ###-###-####'
|
Basic Syntax
|
re.sub(pattern, replacement, string, count=n)
|
Replaces first n occurrences
|
'banana banana banana'
|
'banana banana'
|
Basic Syntax
|
re.sub(pattern, replacement, string, flags=re.IGNORECASE)
|
Case-insensitive replacement
|
'HELLO world'
|
'hello world'
|
Common Substitution Patterns
|
\d
|
#
|
'Order 12345'
|
'Order #####'
|
Common Substitution Patterns
|
\s+
|
' ' (space)
|
'Hello World'
|
'Hello World'
|
Common Substitution Patterns
|
[aeiou]
|
*
|
'Replace vowels'
|
'R*pl*c* v*w*ls'
|
Common Substitution Patterns
|
\bfoo\b
|
bar
|
'foo is here'
|
'bar is here'
|
Common Substitution Patterns
|
(\d{3})-(\d{2})-(\d{4})
|
XXX-XX-\3
|
'123-45-6789'
|
'XXX-XX-6789'
|
Common Substitution Patterns
|
https?://\S+
|
URL_REMOVED
|
'Visit http://example.com'
|
'Visit URL_REMOVED'
|
Using Capture Groups
|
(\w+)@(\w+)\.(\w+)
|
\1[at]\2[dot]\3
|
'john@example.com'
|
'john[at]example[dot]com'
|
Using Capture Groups
|
(\d{2})/(\d{2})/(\d{4})
|
\3-\1-\2
|
'12/31/2024'
|
'2024-12-31'
|
Using Capture Groups
|
(\w)\1+
|
\1
|
'baaaad'
|
'bad'
|
Using Capture Groups
|
(\w+) (\w+)
|
\2 \1
|
'Hello World'
|
'World Hello'
|
Using Capture Groups
|
(?<=\bMr\.|Mrs\.|Dr\.)\s(\w+)
|
***
|
'Dr. John'
|
'Dr. ***'
|
Advanced Substitutions
|
(?<=\d{3})\d{3}(?=\d{4})
|
XXX
|
'1234567890'
|
'123XXX7890'
|
Advanced Substitutions
|
(?<=\b\d{4})\d+
|
XXXX
|
'1234567812345678'
|
'1234XXXXXXXXXXXX'
|
Advanced Substitutions
|
(\w{4})
|
Function based replacement
|
'word'
|
'****'
|
Substituting with Function
|
Function example: Email Censorship
|
Custom function-based replacement
|
'Contact me at john@example.com'
|
'Contact me at john[hidden]'
|