简体   繁体   English

使用正则表达式从字符串中检索数字

[英]retrieve numbers from a string with regex

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. 任何人都知道我在哪里错了。

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

You can use this expression: /((?<h>\\d+)H)?(?<m>\\d+)M(?<s>\\d+)S/ . 你可以使用这个表达式: /((?<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] . 要访问数据: $~[:h]

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"

Me, I'd hashify : 我,我是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} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM