Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 909
Racer Avatar asked Aug 16 '12 14:08

Racer


People also ask

How do I allow special characters in regex?

You can use this regex /^[ A-Za-z0-9_@./#&+-]*$/. To know more about regex ,watch this videos. You can use this regex /^[ A-Za-z0-9_@./#&+-]*$/.

What is escaping in regex?

The backslash in a regular expression precedes a literal character. You also escape certain letters that represent common character classes, such as \w for a word character or \s for a space.

What does ?= Mean in regex?

?= is a positive lookahead, a type of zero-width assertion. What it's saying is that the captured match must be followed by whatever is within the parentheses but that part isn't captured. Your example means the match needs to be followed by zero or more characters and then a digit (but again that part isn't captured).


1 Answers

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]) 
like image 76
Yossi Avatar answered Oct 05 '22 18:10

Yossi