开发者

Pythonic way to do Ruby-like regular expression replace while evaluating the matched string

开发者 https://www.devze.com 2023-03-04 13:17 出处:网络
I have this simple regexp replacement code with a block in it. When Ruby does the gsub the match is passed to the block and whatever is returned from the block is used as replacement.

I have this simple regexp replacement code with a block in it. When Ruby does the gsub the match is passed to the block and whatever is returned from the block is used as replacement.

string = "/foo/bar.####.tif"
string.gsub(/#开发者_运维百科+/) { | match | "%0#{match.length}d" } # => "/foo/bar.%04d.tif"

Is there a way to do this in Python while keeping it concise? Is there a ++replace++ variant that supports lambdas or the with statement?


re.sub accepts a function as replacement. It gets the match object as sole parameter and returns the replacement string.

If you want to keep it a oneliner, a lambda will do work: re.sub(r'#+', lambda m: "%0"+str(len(m.group(0))), string). I'd just use a small three-line def to avoid having all those parens in one place, but that's just my opinion.


I'm not well versed in Ruby, but you might be looking for re.sub

Hope this helps

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号