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 theremodule, which provides the tools for performing regex operationsre.sub(r"test", "sample", text): searches for the patterntestin the stringtextand replaces it withsampleprint(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 remove numbers from a string using Python regex?
- How to match a plus sign in Python regex?
- How to match whitespace in Python regex?
- How to use named groups with regex in Python?
- How to replace all using Python regex?
- How to get all matches from a regex in Python?
- How to match a URL using Python regex?
- How to replace in a file using Python regex?
- How to quote in Python regex?
See more codes...