.* 与 ^ 的非贪婪匹配
Non greedy match of .* with ^
给定字符串:
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 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>
给定字符串:
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 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>