amadain
amadain

Reputation: 2836

Adding backreferenced value to its replacement

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?

Upvotes: 0

Views: 24

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626845

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.

Upvotes: 1

Related Questions