How to replace a substring using regex in Python

The problem: You match a string with your regex, but you need to replace just a portion of it. How can we do this? The trick is simple, put the text you want to replace within “()” which means “group” in regex language. If the regex works, you can replace just that portion by using Python match information, like in the following example:

 1#the first group contains the expression we want to replace
 2pat = "word1s(.*)sword2"
 3test = "word1 will never be a word2"
 4repl = "replace"
 5 
 6import re
 7m = re.search(pat,test)
 8 
 9if m and m.groups() > 0:
10  line = test[0:m.start(1)] + repl + test[m.end(1):len(test)]
11  print line
12else:
13  print "the pattern didn't capture any text"

This will print: 'word1 will never be a word2'

The group to be replaced can be located in any position of the string.