在评估匹配字符串时执行类似 Ruby 正则表达式替换的 Pythonic 方法
我有这个简单的正则表达式替换代码,其中有一个块。当 Ruby 执行 gsub 时 匹配被传递到块,并且从块返回的任何内容都用作替换。
string = "/foo/bar.####.tif"
string.gsub(/#+/) { | match | "%0#{match.length}d" } # => "/foo/bar.%04d.tif"
有没有办法在 Python 中做到这一点,同时保持简洁?是否有支持 lambda 或 with 语句的 ++replace++ 变体?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
re.sub
接受函数作为替换。它获取匹配对象作为唯一参数并返回替换字符串。如果你想让它保持单行,lambda就可以工作:re.sub(r'#+', lambda m: "%0"+str(len(m.group(0))), string )。我只是使用一个小的三行
def
来避免将所有这些括号放在一个地方,但这只是我的意见。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-linedef
to avoid having all those parens in one place, but that's just my opinion.我不太精通 Ruby,但您可能正在寻找 re.sub
希望这有帮助
I'm not well versed in Ruby, but you might be looking for re.sub
Hope this helps