Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby regex MatchData to Integer conversion

Tags:

regex

ruby

I have a string, populated from the *nix "hostname" command, that I need to parse for a number. That's the easy part. The difficulty comes from a need to have to Do Math(tm) on that captured number. Apparently regex captures are always of type MatchData, which doesn't have any math functions like 'add' or 'modulo', nor does it have a method for ".to_i". Currently, in order to Do Math(tm) on my captured number I need to use MatchData's .to_s method to convert the capture to a string, then use String's .to_i to make it an integer. My question is, what's the better way to do this?

hostname = "webserver1337.mycorp.com"
number = hostname.match(/[a-z]+/) 

puts "#{number}, with class #{number.class}" # prints '1337, with class MatchData'

somevar = number + 1 # this will fail horribly

temp1 = number.to_s
number = temp1.to_i

someothervar = number + 1

puts "#{number}, #{someothervar} with class #{number.class}" # prints '1337, 1338 with class FixNum'

This is... slightly ugly. Is there a better/cleaner way to achieve the same thing?


1 Answers

The MatchData object will return the string(s) contained in the match by using []. For example:

hostname = "webserver1337.mycorp.com"
m = hostname.match( /([a-z]+)(\d+)/ ) 
number = m[2].to_i + 1
p m[0], m[1], m[2], number

To do it one shot:

number = hostname.match(/\d+/)[0].to_i + 1
like image 141
FMc Avatar answered Mar 25 '26 01:03

FMc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!