python-regexHow to replace using Python regex?
Python's re
module provides a powerful set of tools for performing regular expression (regex) operations. To replace using Python regex, the re.sub()
function can be used. This function takes three arguments: the pattern to search for, the replacement string, and the string to search in.
Example code
import re
text = "This is a test string"
new_text = re.sub(r"test", "sample", text)
print(new_text)
Output example
This is a sample string
Code explanation
import re
: imports there
module, which provides the tools for performing regex operationsre.sub(r"test", "sample", text)
: searches for the patterntest
in the stringtext
and replaces it withsample
print(new_text)
: prints the new string with the replaced pattern
Helpful links
More of Python Regex
- How to match a YYYY-MM-DD date with Python Regex?
- How to use word boundaries in Python Regex?
- How to match a URL path using Python regex?
- How to match a year with Python Regex?
- How to match a UUID using Python regex?
- How to match whitespace in Python regex?
- How to remove numbers from a string using Python regex?
- How to replace in a file using Python regex?
- How to replace all using Python regex?
- How to perform a zero length match with Python Regex?
See more codes...