Regex string replace
How can you use regular expressions (regex) to find and replace parts of a string? What functions or methods let you perform powerful pattern-based replacements in text?
Using regular expressions (regex) for string replacement allows you to modify text based on patterns rather than fixed values. This is especially useful when you need to replace dynamic or variable content, like numbers, dates, special characters, or repeated words, instead of just exact matches.
In Python, you can use the re module for regex operations. The function re.sub() is commonly used for replacements.
Basic Syntax:
import re
text = "I have 123 apples"
result = re.sub(r"d+", "many", text)
print(result) # Output: I have many apples
- d+ → Matches one or more digits.
- "many" → Replacement text.
- text → The input string.
Using Groups in Replacement:
You can capture parts of a string and reuse them in the replacement.
text = "2025-08-16"
result = re.sub(r"(d{4})-(d{2})-(d{2})", r"//", text)
print(result) # Output: 16/08/2025
Replacing Multiple Patterns:
Regex allows flexibility—e.g., replacing multiple spaces with a single space:
text = "Hello World"
result = re.sub(r"s+", " ", text)
print(result) # Output: Hello World
Advantages of Regex Replace:
- Works with patterns, not just fixed strings.
- Handles complex text transformations easily.
- Saves time compared to manual replacements with loops.
In short, regex string replacement is a powerful tool for text cleaning and formatting, making it ideal for tasks like log processing, data transformation, and input validation.