Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a function like String#scan, but returning array of MatchDatas?

Tags:

ruby

I need a function to return all matches of a regexp in a string and positions at which the matches are found (I want to highlight matches in the string).

There is String#match that returns MatchData, but only for the first match.

Is there a better way to do this than something like

matches = []
begin
  match = str.match(regexp)
  break unless match
  matches << match
  str = str[match.end(0)..-1]
  retry
end
like image 490
Leonid Shevtsov Avatar asked Sep 18 '09 14:09

Leonid Shevtsov


1 Answers

If you just need to iterate over the MatchData objects you can use Regexp.last_match in the scan-block, like:

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

If you really need an array, you can use:

require 'enumerator' # Only needed for ruby 1.8.6
string.enum_for(:scan, regex).map { Regexp.last_match }
like image 177
sepp2k Avatar answered Sep 22 '22 10:09

sepp2k