Ruby正则表达式匹配具有命名捕获支持的枚举器

时间:2013-10-25 17:49:24

标签: ruby regex capture-group

考虑这样的字符串来提取时间信息:

str = "Sun rises at 6:23 am & sets at 5:45 pm; Moon comes up by 7:20 pm and goes down by 3:45 am"

我希望有一个类似扫描的枚举器,但是可以通过扫描获得 MatchData 对象而不是数组。

例如,我可以写:

str.scan( /(?<time>\d:\d{2}) (?<meridiem>am|pm)/ ){ |arr| p arr }

得到:

["6:23", "am"] ["5:45", "pm"] ["7:20", "pm"] ["3:45", "am"]

但是,我想知道是否有这样的事情:

str.match_all( /(?<time>\d:\d{2}) (?<meridiem>am|pm)/ ){ |md| p md }

得到:

#<MatchData "6:23 am" time:"6:23" meridiem:"am"> #<MatchData "5:45 pm" time:"5:45" meridiem:"pm"> #<MatchData "7:20 pm" time:"7:20" meridiem:"pm"> #<MatchData "3:45 am" time:"3:45" meridiem:"am">

previous question中看到答案,但我觉得这是一个不优雅的解决方案。所以检查一下,自从答案发布以来,过去几年情况发生了变化。

1 个答案:

答案 0 :(得分:2)

与您已经看到的答案非常相似,但略有不同。

str = "Sun rises at 6:23 am & sets at 5:45 pm; Moon comes up by 7:20 pm ..."
str.gsub(/(?<time>\d:\d{2}) (?<meridiem>am|pm)/).map{ Regexp.last_match } 

#=> [#<MatchData "6:23 am" time:"6:23" meridiem:"am">, #<MatchData "5:45 pm" ...