Match and capture multiple occurrences of strings in Ruby

April 29, 2008

The real reason I started this blog – to publish little snippets of code! I owe my sensei for help with this one.

class Regexp

    # Matches ALL occurrences of a regular expression in a string.
    # Returns an array of the matches as strings.
    # The regular expression must explicitly use groupings [ like (capturethis) ]
    # to capture matching strings.
    def matchAll( string )
      matchArray = [];
      work_str = string;

      while (m = self.match( work_str ) )
        matchArray << m.captures[0];
        work_str = m.post_match;
      return matchArray;


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: