3

I have a string which returns duration in the below format.

"152M0S" or "1H22M32S"

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

I tried like the below with regex

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

But it does not return as expected. Anyone has any idea where I am going wrong here.

4
  • You will also need to make the H part optional. Commented May 19, 2015 at 19:28
  • please describe how you want to use the resulting data. If you store your time strings in a proper format you can cast them directly to useful strings by using something like Date.format() Commented May 19, 2015 at 19:29
  • 1
    What is the expected output? Commented May 19, 2015 at 19:32
  • Agree with @karthikmanchala. For each of the two examples, show what you expect to get. Commented May 19, 2015 at 19:34

4 Answers 4

2
"1H22M0S".scan(/\d+/)
#=> ["1", "22", "0']
Sign up to request clarification or add additional context in comments.

Comments

1

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">

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

1 Comment

if I need to extract 650.00 from "Rs. 650.00"?
1

If you want to extract numbers, you could do as :

"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"

Comments

1

Me, I'd 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} 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.