【问题标题】:Ruby: substitute all references in part of a string [closed]Ruby:替换字符串的一部分中的所有引用[关闭]
【发布时间】:2013-10-27 08:51:26
【问题描述】:

我想在%{} 内的给定字符串的一部分中将所有. 的引用替换为_。看这个例子:

'example 1.1 %{a.b.c} of {d.e.f}.'

应该换成

'example 1.1 %{a_b_c} of {d_e_f}.'

我必须这样做,因为在较旧的 ruby​​ 上 example %{a.b.c}' % {:'a.b.c' => 'result'} 不起作用。

【问题讨论】:

  • 代码的哪一部分失败了?

标签: ruby regex substring


【解决方案1】:

正如@sawa 建议的,稍作调整:

'example 1.1 %{a.b.c} of {d.e.f}.'.gsub(/{.+?}/) { |s| s.tr '.', '_' }
=> "example 1.1 %{a_b_c} of {d_e_f}."

【讨论】:

    【解决方案2】:

    将 gsub 与块一起使用:

    data = 'example 1.1 %{a.b.c} of {d.e.f}.'
    p data.gsub(/{.+?}/){|x| x.gsub('.','_')} #=> "example 1.1 %{a_b_c} of {d_e_f}."
    

    【讨论】:

    • 好的,你是指整个问题还是只是第二个 gsub?无论如何,为什么 tr 更好?
    • 第二个。因为它更快。
    猜你喜欢
    • 2018-09-20
    • 2016-02-14
    • 1970-01-01
    • 2021-06-16
    • 2022-07-18
    • 2021-12-15
    • 1970-01-01
    • 1970-01-01
    • 2015-04-06
    相关资源
    最近更新 更多