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

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

There is a 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 
+6
ruby
source share
4 answers

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

 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 } 
+10
source share

Do you really need a position or is it enough to replace matches on the fly?

 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>') 

=> "I will let you finish, but Beyonce had one of the best music videos of all time!"

+2
source share

Use the captures method in a successful match.

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

=> ["f," "oobar"]

+1
source share

I think that at least you can improve your code a bit:

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

All Articles