我有一个字符串,它以以下格式返回持续时间。
"152M0S" or "1H22M32S"
我需要将它中的小时、分钟和秒提取为数字。
我尝试使用正则表达式,如下所示。
video_duration.scan(/(\d+)?.(\d+)M(\d+)S/)
但是它没有返回预期的结果。有人知道我在这里做错了什么吗?
"1H22M0S".scan(/\d+/)
#=> ["1", "22", "0']
/((?<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">
$~[:h]
。"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"
我会哈希化:
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}
H
部分可选。 - HamZa