Escape special chars in RegEx?

regex, ruby, ruby-on-rails

Solution

You should use `Regexp.escape`

regex = /#{Regexp.escape(params[:text])}/
# in rails models/controllers with mongoid use:
# ::Regexp.escape(params[:text]) instead. ([more info][2])

Problem

I have a form, that sends the contents of a text field to my Rails application and I have to generate a regular expression of this string. I tried it like this: ``` regex = /#{params[:text]}/ ``` In general this is working, but if brackets or special characters are contained in the string, this method will not work. I don't want Rails to take care of the chars. They should be escaped automatically. I tried it like this: ``` /\Q#{params[:text]}\E/ ``` but this isn't working either.

Original source