0

I am trying to add a number from a backreference to another number, but I seem to get only concatenation:

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

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

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

I tried also using to_i on the backreferenced value, but I can't get the extracted value to add. Do I need to do something to the value to make it addable?

sawa
  • 165,429
  • 45
  • 277
  • 381
amadain
  • 2,724
  • 4
  • 37
  • 58

1 Answers1

1

If you are manipulating XML, I'd suggest using some specific library for that. In this answer, I just want to show how to perform operations on the submatches.

You can sum up the values inside a block:

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

See IDEONE demo

If we use {|m|...} we won't be able to access captured texts since m is equal to Regexp.last_match[0].to_s.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563