Reputation: 2210
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.
Upvotes: 5
Views: 1757
Reputation: 4382
Even simpler is just using .next
"foo_1".next #=> foo_2
"bar_1 foo_1".next #=> bar_1 foo_2
So, you could simplify your regex and block like so
"bar_1 foo_2".gsub(/\bfoo_\d+\b/) {|f| f.next }
Upvotes: 2
Reputation: 1590
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.
Upvotes: 4
Reputation: 44346
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
Upvotes: 4