【问题标题】:Passing replacement string as parameter [closed]将替换字符串作为参数传递[关闭]
【发布时间】:2014-03-05 14:29:50
【问题描述】:

我有一个代码:

require 'pp'

def unquote_string(string)
    if (string.is_a?(String))
        string.gsub(/\\/,'')
    else 
        string
    end
end

def filter_array_with_substitution_and_replacement(array,options={})
    pp options
    return array unless %w(filterRegex substitudeRegex replacementExpression).any? {|key| options.has_key? key}
    puts "I will substitude!"
    filterRegex = options["filterRegex"]
    substitudeRegex = options["substitudeRegex"]
    replacementExpression = options["replacementExpression"]
    pp "I have: #{replacementExpression}"
    array.select{|object| 
        object =~ filterRegex
    }.map!{|object| 
        object.sub!(substitudeRegex,unquote_string(replacementExpression))
    }
end


def sixth_function
    array = %w(onetwo onethree onefour onesix none any other)
    filterRegex = /one/
    substitudeRegex = /(one)(\w+)/
    replacementExpression = '/#{$2}.|.#{$1}/'
    options = {
        "filterRegex" => filterRegex,
        "substitudeRegex" => substitudeRegex,
        "replacementExpression" => replacementExpression
    }   
    filter_array_with_substitution_and_replacement(array,options)
    pp array
end

def MainWork
   sixth_function()
end

MainWork()

输出:

{"filterRegex"=>/one/,
 "substitudeRegex"=>/(one)(\w+)/,
 "replacementExpression"=>"/\#{$2}.|.\#{$1}/"}
I will substitude!
"I have: /\#{$2}.|.\#{$1}/"
smb192168164:Scripts mac$ ruby rubyFirst.rb
{"filterRegex"=>/one/,
 "substitudeRegex"=>/(one)(\w+)/,
 "replacementExpression"=>"/\#{$2}.|.\#{$1}/"}
I will substitude!
"I have: /\#{$2}.|.\#{$1}/"
["/\#{$2}.|.\#{$1}/",
 "/\#{$2}.|.\#{$1}/",
 "/\#{$2}.|.\#{$1}/",
 "/\#{$2}.|.\#{$1}/",
 "none",
 "any",
 "other"]

这是不正确的,因为带有替换的字符串有元字符引用。如何更正取消引用此字符串replacementExpression

替换后数组的期望输出:

["two.|.one/",
 "three.|.one/",
 "four.|.one/",
 "six.|.one/",
 "none",
 "any",
 "other"]

【问题讨论】:

  • 你想要的输出是什么?
  • @Chowlett,我编辑了帖子
  • 顺便说一句,您应该为sixth_function() 选择一个更有用的名称。
  • @Josh 这是我的第一个 ruby​​ 文件,我在其中测试所有内容。是的,如果您愿意,我必须将其称为“test_one”或“test_two”
  • @DaniëlKnippers,那么,如何通过取消引用来解决此任务? Chowlett 的 \1 捕获组运行良好

标签: ruby quotes metacharacters


【解决方案1】:

忘记unquote_string - 你只希望你的replacementExpression'\2.|.\1'

"onetwo".sub(/(one)(\w+)/, '\2.|.\1')
#=> "two.|.one"

【讨论】:

  • 谢谢,就像一个魅力!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-14
  • 2020-05-30
  • 2017-08-10
  • 2020-05-01
  • 2014-01-21
相关资源
最近更新 更多