非贪婪匹配。*与^

时间:2017-05-17 03:56:05

标签: python regex placeholder regex-greedy non-greedy

给出字符串:

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)

1 个答案:

答案 0 :(得分:4)

如果您在明星之后添加问号,则会使其变得非贪婪。

\^.*?\^

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>