Mobidi Mobidi - 1 year ago 67
Ruby Question

Complex regex in ruby

I have a complexe regex to make in ruby.

str = '1:2-2:1015-3:1007,=,0-4:2,|,3'
regex = /(\d+):|(\d+),\|,(\d+)/

My goal is to find only certain digit (thoose before ':' for exemple) and add a number to all of them.

Exemple if I want to add 20 to all of them my str would look like this :

str = '21:2-22:1015-23:1007,=,0-24:22,|,23'

I can find them with this regex but I can't find how to make an addition

I tried a few things like this :

str.gsub(/(\d+):/){|m| m.to_i + 30}
Result : "312-321015-331007,=,0-3432"

It delete me the ':', the '|' and didn't make the addition for the last digit.

I'm sure I'm doing it wrong perhap with map and scan I could do something right ?

Thanks for your help, I hope my explanations are clear.

Edit : The two solution bellow are correct for me, do not hesitate to read both of them

Answer Source

There is a lot easier way:

▶ str = '1:2-2:1015-3:1007,=,0-4:2,|,3'
▶ regex = /(\d+)(?=:)|(\d+)(?=,\|,\d)|(?<=\d,\|,)(\d+)/
▶ str.gsub(regex) { |m| (m.to_i + 20).to_s }
#⇒ "21:2-22:1015-23:1007,=,0-24:22,|,23"

The trick here is that we match digits only to make them easy to subst. Positive lookaheads help to catch those digits (note, that there are now 3 different conditions, to always match the single number.)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download