Extract numbers from string with regex

I have a string that returns duration in the following format.

"152M0S" or "1H22M32S"

      

I need to extract hours, minutes and seconds from it as numbers.

I tried as below with regex

video_duration.scan(/(\d+)?.(\d+)M(\d+)S/)

      

But it doesn't come back as expected. Anyone have an idea where I am going wrong.

+3


source to share


4 answers


You can use this expression /((?<h>\d+)H)?(?<m>\d+)M(?<s>\d+)S/

.

"1H22M32S".match(/((?<h>\d+)H)?(?<m>\d+)M(?<s>\d+)S/)
#=> #<MatchData "1H22M32S" h:"1" m:"22" s:"32">

"152M0S".match(/((?<h>\d+)H)?(?<m>\d+)M(?<s>\d+)S/)
#=> #<MatchData "152M0S" h:nil m:"152" s:"0">

      



The question mark after the group makes it optional. To access the data: $~[:h]

.

+1


source


"1H22M0S".scan(/\d+/)
#=> ["1", "22", "0']

      



+2


source


If you want to extract numbers, you can do this:

"1H22M32S".match(/(?<hour>(\d+))H(?<min>(\d+))M(?<sec>(\d+))S/i).captures
# => ["1", "22", "32"]
"1H22M32S".match(/(?<hour>(\d+))H(?<min>(\d+))M(?<sec>(\d+))S/i)['min']
# => "22"
"1H22M32S".match(/(?<hour>(\d+))H(?<min>(\d+))M(?<sec>(\d+))S/i)['hour']
# => "1"

      

+1


source


Me, I would hashify

:

def hashify(str)
  str.gsub(/\d+[HMS]/).with_object({}) { |s,h| h[s[-1]] = s.to_i }
end

hashify "152M0S"    #=> {"M"=>152, "S"=>0} 
hashify "1H22M32S"  #=> {"H"=>1, "M"=>22, "S"=>32} 
hashify "32S22M11H" #=> {"S"=>32, "M"=>22, "H"=>11} 
hashify "1S"        #=> {"S"=>1} 

      

+1


source







All Articles