向其替换添加反向引用值

Adding backreferenced value to its replacement

我正在尝试将一个数字从反向引用添加到另一个数字,但我似乎只能得到连接:

textStr = "<testsuite errors=\"0\" tests=\"4\" time=\"4.867\" failures=\"0\" name=\"TestRateUs\">"

new_str = textStr.gsub(/(testsuite errors=\"0\" tests=\")(\d+)(\" time)/, '+4')

# => "<testsuite errors=\"0\" tests=\"4+4\" time=\"4.867\" failures=\"0\" name=\"TestRateUs\">"

我也尝试在反向引用值上使用 to_i,但我无法获取要添加的提取值。我需要对值做些什么才能使其可添加吗?

如果您正在操纵 XML,我建议为此使用一些特定的库。在这个答案中,我只是想展示如何对子匹配进行操作。

您可以对块内的值求和:

textStr="<testsuite errors=\"0\" tests=\"4\" time=\"4.867\" failures=\"0\" name=\"TestRateUs\">"
new_str = textStr.gsub(/(testsuite errors=\"0\" tests=\")(\d+)(\" time)/) do
    Regexp.last_match[1] + (Regexp.last_match[2].to_i + 4).to_s + Regexp.last_match[3]
end
puts new_str

IDEONE demo

如果我们使用 {|m|...},我们将无法访问捕获的文本,因为 m 等于 Regexp.last_match[0].to_s