I have a large file in a ruby variable, it follows a common pattern like so:
// ...
// comment
$myuser['bla'] = 'bla';
// comment
$myuser['bla2'] = 'bla2';
// ...
I am trying to given a ‘key’ replace the ‘value’
This replaces the entire string how do I fix it? Another method I thought is to do it in two steps, step one would be to find the value within the quotes then to perform a string replace, what’s best?
def keyvalr(content, key, value)
return content.gsub(/\$bla\[\'#{key}\'\]\s+\=\s+\'(.*)\'/) {|m| value }
end
The
.*is greedy and consumes as much as possible (everything until the very last'). Make that.a[^']then it is impossible for it to go past the first closing'.I also added parentheses to capture everything except for the value, which is to be replaced. The first set of parens will correspond to
\1and the second to\2. So that you replace the match of this with: