How to use ruby variables in regular expressions

Posted: 08/02/2008

If you do not know the pattern that you are trying to match ahead of time (e.g. it is some form of user input), you can construct a regex from a string:

  str = "this string has ruby in it"
  re = "ruby"
  str =~ /#{re}/    # => 16

You can also combine components to create a new pattern:

  a = 'ruby'
  b = 'on rails'
  str = "this string has ruby on rails in it"
  str.match(/#{a} #{b}/)    # => true

If you are looking for a way to create patterns from combinations of common elements, and the elements are not derived from input, it is just as easy to combine Regexp objects:

  a = /ruby/
  b = /on rails/
  str = "this string has ruby on rails in it"
  str.match(/#{a} #{b}/)  # => true

About Me

I'm a skier, web developer, entrepreneur, freelancer, and all around stand-up guy living in Manhattan. This is me, repping one of my favorite shirts...

Follow me on twitter or send me an email.

All Posts