Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I search, increment, and replace integer substrings in a Ruby string?

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.

like image 400
David Carney Avatar asked May 13 '11 14:05

David Carney


2 Answers

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

like image 137
Alin Purcaru Avatar answered Nov 14 '22 22:11

Alin Purcaru


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.

like image 36
Thomas Hupkens Avatar answered Nov 14 '22 23:11

Thomas Hupkens