Scott H Scott H - 11 months ago 32
Python Question

Replace word between two substrings (keeping other words)

I'm trying to replace a word (e.g.

) if it falls between two substrings (e.g.
) however other words are present which need to be kept.

string = "<temp>The sale happened on February 22nd</temp>"

The desired string after the replace would be:

Result = <temp>The sale happened {replace} February 22nd</temp>

I've tried using regex, I've only been able to figure out how to replace everything lying between the two
tags. (Because of the

result = re.sub('<temp>.*?</temp>', '{replace}', string, flags=re.DOTALL)

may appear later in the string not between
and I wouldn't want to replace this.

re.sub('(<temp>.*?) on (.*?</temp>)', lambda x:" <replace> ", string, flags=re.DOTALL)


<temp>The sale happened <replace> February 22nd</temp>


Changed the regex based on suggestions by Wiktor and HolyDanna.

P.S: Wiktor's comment on the question provides a better solution.