alv*_*vas 1 python regex placeholder non-greedy regex-greedy
给定字符串:
s = "Why did you foo bar a <b>^f('y')[f('x').get()]^? and ^f('barbar')^</b>"
Run Code Online (Sandbox Code Playgroud)
如何用字符串替换^f('y')[f('x').get()]^和^f('barbar')^,例如PLACEXHOLDER?
所需的输出是:
Why did you foo bar a <b>PLACEXHOLDER? and PLACEXHOLDER</b>
Run Code Online (Sandbox Code Playgroud)
我试过了,re.sub('\^.*\^', 'PLACEXHOLDER', s)但.*贪婪,它匹配,^f('y')[f('x').get()]^? and ^f('barbar')^并输出:
您为什么foo禁止PLACEXHOLDER
可能存在多个未知数字的子字符串,这些子字符串由进行编码,\^因此不希望这样做:
re.sub('(\^.+\^).*(\^.*\^)', 'PLACEXHOLDER', s)
Run Code Online (Sandbox Code Playgroud)
如果在星号后面添加问号,它将使其不贪心。
\^.*?\^
Run Code Online (Sandbox Code Playgroud)
http://www.regexpal.com/?fam=97647
Why did you foo bar a <b>^f('y')[f('x').get()]^? and ^f('barbar')^</b>
Run Code Online (Sandbox Code Playgroud)
正确替换为
Why did you foo bar a <b>PLACEXHOLDER? and PLACEXHOLDER</b>
Run Code Online (Sandbox Code Playgroud)