【问题标题】:Ruby gsub with index/offset?带有索引/偏移量的Ruby gsub?
【发布时间】:2012-08-25 08:45:21
【问题描述】:

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

我喜欢你,你,你,还有你。

我想得到这个输出:

我喜欢你1、你2、你3和你4。

我知道我可以使用\1\2 等来匹配括号中的字符,但是有没有像\i\n 这样的东西可以提供当前匹配的编号?

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

【问题讨论】:

  • 示例代码假设 "you" 很容易被您修改以替换任何需要的目标或正则表达式。

标签: ruby regex string gsub


【解决方案1】:

我们可以将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.

【讨论】:

  • each_with_indexwith_index 都是无名英雄。
  • 我承认我忽略了最新的!
  • 我什至没有注意到with_index 可以与subgsub 一起使用!
  • 我觉得这太酷了! foo = 'I like you, you, you, and you.'.gsub(/\byou\b/).with_index { |m, i| i == 2 ? "#{m}#{1+i}" : "#{m}" },输出#=> "I like you, you, you3, and you."
  • 漂亮!谢谢你:)
【解决方案2】:

这可行,但很丑:

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."

【讨论】:

  • 如果替换字符串也包含像 \1 这样的值怎么办?如何在匹配的字符串中用 $1 正确替换它?例如: "hello".gsub(/(ello)/, "i and h\1") 将产生 "hi and hello"。如何在块中考虑这些替换?
【解决方案3】:

这有点老套,但你可以使用一个变量,在传递给 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.

【讨论】:

  • 相同(丑陋!)答案,相同时间 => +1 :)
  • 如果替换字符串也包含\1 之类的值怎么办?如何在匹配的字符串中用$1 正确替换它?例如:"hello".gsub(/(ello)/, "i and h\1") 将产生“hi and hello”。如何在块中考虑这些替换?
  • @MattHuggins:为每个组调用该块。使用"i and h#{match}" 将产生您正在寻找的东西
  • 我很好奇为什么有人会投反对票。评论会很有帮助,所以我可以解决这个问题
猜你喜欢
  • 2012-06-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-19
  • 2015-12-21
  • 2017-09-14
  • 2011-08-04
  • 1970-01-01
相关资源
最近更新 更多