在两个子字符串之间替换单词(保留其他单词)

3

我正在尝试替换一个单词(例如 on),如果它在两个子字符串(例如 <temp></temp>)之间出现,但其他需要保留的单词也存在。

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

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

我尝试使用正则表达式,但只能找到如何替换两个<temp>标签之间的所有内容(因为有.*?)。

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

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


它落在两个子字符串之间 - 是哪两个子字符串?您能否提供原始字符串和替换后的字符串的示例? - gaganso
遗憾的是,在re模块中没有对\G和\K提供支持。 - Sebastian Proske
您的期望输出不是有效的XML。您不能打开<replace>元素,然后关闭</temp> - user5547025
3
只有一个 on 需要替换还是所有的 on 都需要替换?如果您想将所有的空格+on+空格替换为空格+{replace}+空格,请使用re.sub('<temp>(.*?)</temp>', lambda m: "<temp>{}</temp>".format( m.group(1).replace(" on ", " {replace} ") ), string, flags=re.DOTALL) - Wiktor Stribiżew
非常好,完美运作,谢谢! - Scott H
显示剩余3条评论
2个回答

1
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的建议,更改了正则表达式。

P.S:Wiktor在问题评论中提供了更好的解决方案。


正则表达式实际上不太合适,但思路是正确的。 - Wiktor Stribiżew
@WiktorStribiżew,谢谢。您能否详细说明一下?如果您建议正确的正则表达式,我将替换它,否则如果您要回答这个问题,那么我将根据您的答案删除我的答案。 - gaganso
这个可以工作,但是是否可能仅限于<temp></temp>之间进行替换?同时也会替换标签外的内容。 - Scott H
1
一两条注释:此正则表达式('(<temp>.*?)on(.*?</temp>)')将删除<temp>....</temp>字符串内的1个on子字符串,2)on将像这样被删除 - <temp>The sale postponed on February 22nd</temp> -> <temp>The sale postp<replace>ed on February 22nd</temp>。我猜你想要的是rr'(<temp>.*?) on (.*?</temp>)',并用x.group(1)+" <replace> "+x.group(2)替换,3)这不考虑嵌套的<temp>标记。 - Wiktor Stribiżew
1
如果在单行中有多个临时构造,且它们之间没有一个(但不在其中),则此方法可能会失败。我还建议在“on”周围使用单词边界。 - Sebastian Proske
显示剩余2条评论

0
尝试使用lxml
from lxml import etree

root = etree.fromstring("<temp>The sale happened on February 22nd</temp>")
root.text = root.text.replace(" on ", " {replace} ")
print(etree.tostring(root, pretty_print=True))

输出:

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

我认为你需要编写代码来查找<temp标签,因为它们可能是某个较大文件的一部分。 - Blckknght
“string” 是有效的 XML。让我们按照问题所写的方式来处理,不要让我们猜测。 - user5547025

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接