Pregunta

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.

¿Fue útil?

Solución

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

Otros consejos

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.

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 }
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top