I have a lot of documents that look like this:
foo_1 foo_2
foo_3
bar_1 foo_4 ...
And I want to convert them by taking all instances of foo_[X]
and replacing each of them with foo_[X+1]
. In this example:
foo_2 foo_3
foo_4
bar_1 foo_5 ...
Can I do this with gsub and a block? If not, what's the cleanest approach? I'm really looking for an elegant solution because I can always brute force it, but feel there's some regex trickery worth learning.
I don't know Ruby (at all), but something similar to this should work:
"foo_1 foo_2".gsub(/(foo_)(\d+)/) {|not_needed| $1 + ($2.to_i + 1).to_s}
LE: I actually made it work: http://codepad.org/Z5ThOvTr
If you just want the numbers following foo_ to be changed
str.gsub(/(?<=foo_)\d+/) {|num| num.to_i+1}
Note: Look-behinds will only work in versions or Ruby >= 1.9.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With