给定字符串:
s = "Why did you foo bar a <b>^f('y')[f('x').get()]^? and ^f('barbar')^</b>"
如何替换 ^f('y')[f('x').get()]^ 和 ^f('barbar')^ 带有一个字符串,例如PLACEXHOLDER?
期望的输出是:
Why did you foo bar a <b>PLACEXHOLDER? and PLACEXHOLDER</b>
我已经尝试过 re.sub('\^.*\^', 'PLACEXHOLDER', s) 但 .* 是贪婪的并且匹配, ^f('y')[f('x').get()]^?和 ^f('barbar')^ 和输出:
你为什么要 foo bar a PLACEXHOLDER
可以有多个由 \^ 编码的未知数字子串,因此不需要硬编码:
re.sub('(\^.+\^).*(\^.*\^)', 'PLACEXHOLDER', s)
请您参考如下方法:
如果在星号后面加一个问号,就会变成非贪婪的。
\^.*?\^
http://www.regexpal.com/?fam=97647
Why did you foo bar a <b>^f('y')[f('x').get()]^? and ^f('barbar')^</b>
正确替换为
Why did you foo bar a <b>PLACEXHOLDER? and PLACEXHOLDER</b>
