與^

2017-05-17 19 views
1

的非貪婪匹配*鑑於字符串:與^

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')^和輸出:

你爲什麼Foo bar將一PLACEXHOLDER

可以有多個未知數字的子串,由\^編碼,因此硬編碼不是d希望:

re.sub('(\^.+\^).*(\^.*\^)', 'PLACEXHOLDER', s) 

回答

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>