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

Mat*_*ins 16 ruby regex string gsub

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

我喜欢你,你,你,你.

我想最终得到这个输出:

我喜欢你1,you2,you3和you4.

我知道我可以使用\1,\2等匹配括号字符,但有类似的东西\i\n将提供当前匹配的数量?

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

the*_*Man 44

我们可以链接with_indexgsub():

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

哪个输出:

I like you1, you2, you3, and you4.
Run Code Online (Sandbox Code Playgroud)

  • 'each_with_index`和`with_index`都是无名英雄. (2认同)