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

时间:2009-09-18 14:08:49

标签: ruby

我需要一个函数来返回字符串中匹配的所有匹配项(我希望突出显示匹配项)。

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

有没有比

更好的方法来做到这一点
matches = []
begin
  match = str.match(regexp)
  break unless match
  matches << match
  str = str[match.end(0)..-1]
  retry
end

4 个答案:

答案 0 :(得分:11)

如果您只需要遍历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 }

答案 1 :(得分:2)

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

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

=&GT; “我会让你完成,但 Beyonce 有史以来最好的最佳音乐视频!”

答案 2 :(得分:1)

成功匹配时使用captures方法。

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

=&GT; [&#34; F,&#34;&#34; oobar&#34;]

答案 3 :(得分:0)

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

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