February 12, 2008

Ruby regexp search

I just started learning ruby, and have run into the problem that the Regexp class doesn't have a search method for matching all occurances of a pattern in a string. With a little help from ruby-lang irc, I am now using this extension for Regexp:

class Regexp
def search(string, offset=0)
string.scan(self) { |txt| yield Regexp.last_match }

Ruby 1.9 has a match method that takes an offset, but it only returns a single MatchData object. The above is much simpler to use IMHO.