带有索引/偏移量的Ruby gsub?

时间:2012-08-30 15:06:46

标签: ruby regex string gsub

Ruby的String#gsub方法是否提供了包含替换索引的方法?例如,给定以下字符串:

  

我喜欢你,你,你,你。

我想最终得到这个输出:

  

我喜欢你,你,你,你和你。

我知道我可以使用\1\2等来匹配括号中的字符,但有\i\n之类的字符可以提供目前的比赛?

值得一提的是,我的实际术语并不像“你”那么简单,因此假定搜索词是静态的替代方法是不够的。

3 个答案:

答案 0 :(得分:43)

我们可以将with_index链接到gsub()以获取:

foo = 'I like you, you, you, and you.'.gsub(/\byou\b/).with_index { |m, i| "#{m}#{1+i}" }
puts foo

输出:

I like you1, you2, you3, and you4.

答案 1 :(得分:3)

这很有效,但很难看:

n = 0; 
"I like you, you, you, and you.".gsub("you") { val = "you" + n.to_s; n+=1; val }
=> "I like you0, you1, you2, and you3."

答案 2 :(得分:3)

这有点hacky,但你可以使用一个在传递给gsub的块内增量的变量

source = 'I like you, you, you, and you.'
counter = 1
result = source.gsub(/you/) do |match|
  res = "#{match}#{counter}"
  counter += 1
  res
end

puts result
#=> I like you1, you2, you3, and you4.