【问题标题】:Replace regular expression match with result of applying a function用应用函数的结果替换正则表达式匹配
【发布时间】:2012-08-11 23:36:47
【问题描述】:

我以前在 ruby​​ 中做过类似的事情:

text.gsub!( SOME REGEX ) do |s|
    s.SOME_STRING_STUFF
end

我知道在 python 中没有像 ruby​​ 那样“做”的东西,但我不知道如何做这样的事情!

【问题讨论】:

  • 我不确定 sn-p 在做什么——但如果你想要 Python 中的上下文包装器; with statement 就是这样做的。

标签: python ruby regex python-2.7


【解决方案1】:

只需将函数作为替换传递给re.sub

print(re.sub(r't[^t].', lambda m: m.group(0)[::-1], 'testtext')) # settxett

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-25
    • 1970-01-01
    • 1970-01-01
    • 2015-11-30
    • 2012-05-16
    相关资源
    最近更新 更多