是否有类似String#scan的函数,但返回MatchDatas数组?

我需要一个函数来返回字符串中正则表达式的所有匹配项以及找到匹配项的位置(我想突出显示字符串中的匹配项)。

String#match返回MatchData,但仅适用于第一个匹配。

有没有比这更好的方法来做到这一点

matches = [] begin match = str.match(regexp) break unless match matches << match str = str[match.end(0)..-1] retry end 

如果您只需要遍历MatchData对象,则可以在扫描块中使用Regexp.last_match,例如:

 string.scan(regex) do match_data = Regexp.last_match do_something_with(match_data) end 

如果你真的需要一个数组,你可以使用:

 require 'enumerator' # Only needed for ruby 1.8.6 string.enum_for(:scan, regex).map { Regexp.last_match } 

你真的需要这个位置还是足以在飞行中取代比赛?

 s="I'mma let you finish but Beyonce had one of the best music videos of all time!" s.gsub(/(Beyonce|best)/, '\1') 

=>“我想让你完成,但碧昂丝有史以来最好的音乐video之一!”

成功匹配时使用captures方法。

 "foobar".match(/(f)(oobar)/).captures 

=> [“f,”“oobar”]

我想至少你可以稍微增强你的代码:

 matches = [] while(match = str.match(regexp)) matches << match str = match.post_match end