如果一个词落在两个子串之间(例如on&<temp>),我试图替换它(例如</temp>)。

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

替换后所需的字符串为:
Result = <temp>The sale happened {replace} February 22nd</temp>

我试过使用regex,我只知道如何替换两个<temp>标记之间的所有内容。(因为.*?
result  = re.sub('<temp>.*?</temp>', '{replace}', string, flags=re.DOTALL)

但是on可能出现在字符串的后面,而不是<temp></temp>之间,我不想替换它。

最佳答案

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

输出:
<temp>The sale happened <replace> February 22nd</temp>

编辑:
根据Wiktor和HolyDanna的建议更改了regex。
附:威克托对这个问题的评论提供了更好的解决办法。

关于python - 在两个子字符串之间替换单词(保留其他单词),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38500616/

10-11 22:49
查看更多