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 to share
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 to share