Code Like Zell

How to use Ruby variables in regular expressions

Posted 27 September 2007.

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 =~ /#{Regexp.escape(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

Index

Sponsored by OpenKit