【发布时间】:2016-11-24 19:59:09
【问题描述】:
如果某个单词(例如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> 之间,我不想替换它。
【问题讨论】:
-
它位于两个子字符串之间 - 哪两个子字符串?你能提供一个原始字符串和替换字符串的例子吗?
-
遗憾的是,重新模块中不支持 \G 和 \K。
-
您想要的输出不是有效的 XML。你不能打开
<replace>元素然后关闭</temp>。 -
它不是 XML,只是为我自己的日后提供的指标
-
只有一个
on还是所有ons 可以替换?如果要将所有空格+on+空格替换为空格+{replace}+空格,请使用re.sub('<temp>(.*?)</temp>', lambda m: "<temp>{}</temp>".format( m.group(1).replace(" on ", " {replace} ") ), string, flags=re.DOTALL)。