python-regexHow to replace a certain group using Python regex?
Regex (regular expressions) can be used to replace a certain group of characters in a string using Python. To do this, 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
string = "Hello World!"
new_string = re.sub("World", "Universe", string)
print(new_string)
Output example
Hello Universe!
Code explanation
import re
: imports there
module which contains there.sub()
functionstring = "Hello World!"
: assigns the string to be searched to thestring
variablenew_string = re.sub("World", "Universe", string)
: uses there.sub()
function to search for the patternWorld
in thestring
variable and replace it withUniverse
print(new_string)
: prints the new string with the replaced pattern
Helpful links
More of Python Regex
- How to match everything between two words with Python regex?
- How to match a YYYY-MM-DD date with Python Regex?
- How to match a UUID using Python regex?
- How to match a hex number with regex in Python?
- How to match a year with Python Regex?
- How to match whitespace in Python regex?
- How to match one or more occurence in Python regex?
- How to match certain amount of digits with Python regex?
- How to match the beginning of a line with Python regex?
- How to use backslash in Python regex?
See more codes...