When your regular expression is composed, you can put brackets around the parts that you want to capture and call when replacing.
The example below shows this method. To be clear, you first define < and > with parentheses, and between them is a regular expression for the word undefined size. For substitution, you recall the first time you capture an input, then “hh” appears, and then you recall the second instance of the captured input string. Positions are called using the backslash \ , followed by the instance number.
import re test = "<test>" myre = r'(<)\w*(>)' mysub = r'\1hh\2' newstring = re.sub(myre, mysub, string)
source share