Replace match inside tags The problem I want to solve is to replace a given string inside tags.

For example, if I'm given:


  Some text abc [tag]some text abc, more text abc[/tag] still some more text


I want to replace abc for def but only inside the tags, so the output would be:


  Some text abc [tag]some text def, more text def[/tag] still some more text


We may assume that the tag nesting is well formed. My solution is the following:

def replace_inside(text):
    i = text.find('[tag]') 
    while i &gt;= 0:
        j = text.find('[/tag]', i+1)
        snippet = text[i:j].replace('abc', 'def')
        text = text[:i] + snippet + text[j:]
        i = text.find('[tag]', j) 
    return text


I was wondering if it can be solved in a more elegant way, for example, using regex.
Your code is incorrect. See the following case:

print replace_inside("[tag]abc[/tag]abc[tag]abc[/tag]")


You can indeed use regular expressions

pattern = re.compile(r"\[tag\].*?\[/tag\]")
return pattern.sub(lambda match: match.group(0).replace('abc','def') ,text)