How to Replace Text with Regex
Use regex substitution to find and replace patterns in text, including capture group references.
Problem
You need to replace multiple occurrences of a pattern in text, possibly reusing parts of the matched text in the replacement.
Prerequisites
- Understanding of regex patterns
- Knowledge of capture groups
Steps
-
1. Define the search pattern
Write a regex that matches the text you want to replace. Use capture groups for parts you want to reuse in the replacement. The g flag is needed to replace all occurrences; without it, only the first match is replaced.
Inputpattern: (\w+)@(\w+)Outputcaptures name and domain -
2. Define the replacement
The replacement can be a literal string or a function. Use $1, $2, etc. to reference capture groups in the replacement string. A function receives match details and can return dynamic replacements based on the matched content.
Inputreplace with: $2.$1Outputswaps name and domain -
3. Execute and verify
Run the replacement and inspect the output. Check that all intended matches were replaced and that no unintended matches were affected. If the result is wrong, adjust the pattern or replacement and retry.
Input[email protected] → example.aliceOutputverified
Expected result
Text with all matching patterns replaced according to the replacement specification.
Common errors
- Only first occurrence replaced
- Add the g (global) flag to replace all occurrences. Without g, replace only changes the first match.
- Replacement includes literal $1 instead of captured text
- Ensure the replacement string uses the correct syntax for capture group references. Different languages use $1 vs \1.
Troubleshooting
- If too many replacements occur, make the pattern more specific.
- Use a replacement function for complex logic that cannot be expressed as a simple string.
Security limits
- Regex replacement on untrusted input can be vulnerable to ReDoS. Use safe patterns and consider a timeout.
Related tools
Related glossary
Related tasks
Ready to run it?