【发布时间】:2017-10-16 08:24:55
【问题描述】:
给定字符串:
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()]^? and ^f('barbar')^ 并输出:
你为什么把一个 PLACEXHOLDER
可能有多个未知数字的子字符串由\^ 编码,因此不需要硬编码:
re.sub('(\^.+\^).*(\^.*\^)', 'PLACEXHOLDER', s)
【问题讨论】:
标签: python regex placeholder regex-greedy non-greedy