Racer
Racer

Reputation: 554

Escape special chars in RegEx?

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.

Upvotes: 34

Views: 16167

Answers (2)

Yossi
Yossi

Reputation: 12090

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])

Upvotes: 56

Stefan
Stefan

Reputation: 114138

Regexp.escape escapes special characters:

params[:text] = "[foo-bar]"
Regexp.new(Regexp.escape(params[:text]))
# => /\[foo\-bar\]/

Upvotes: 9

Related Questions