How to add 2 ruby regex patterns together

Here’s a monkeypatch for ruby’s Regexp class that will allow you to concatenate 2 (or more) regex patterns together:


class Regexp
  def +(r)
    Regexp.new(source + r.source)
  end
end

It comes in very useful when doing something like the following…


protocol_rgx = /^http:\/\//
google_search_rgx = /.*\.google\.com$/
possible_google_domains = []
possible_google_domains << "http://www.google.com"
possible_google_domains << "http://images.google.com"
possible_google_domains << "http://finance.google.com"
possible_google_domains << "http://video.google.com"
possible_google_domains << "http://www.bing.com"

possible_google_domains.each do |domain|
  domain.scan(protocol_rgx + google_search_rgx).each do |match|
    puts match
  end
end

In the above example, I have 2 patterns; one for matching the protocol section of a url (protocol_rgx) and another to match the normal google search domain (google_search_rgx). When I add them together using the monkeypatch above and then scan a string with the resulting concatenated pattern, it will do exactly what you expect it to do: match the string against the full pattern. So the output of the above example is:

http://www.google.com

http://images.google.com

http://finance.google.com

http://video.google.com


The string we put in matches all the domains apart from the bing domain.

Enjoy adding regex patterns together!

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>