Convert a string to regular expression ruby

cmthakur picture cmthakur · Dec 28, 2011 · Viewed 64.4k times · Source

I need to convert string like "/[\w\s]+/" to regular expression.

"/[\w\s]+/" => /[\w\s]+/

I tried using different Regexp methods like:

Regexp.new("/[\w\s]+/") => /\/[w ]+\//, similarly Regexp.compile and Regexp.escape. But none of them returns as I expected.

Further more I tried removing backslashes:

Regexp.new("[\w\s]+") => /[w ]+/ But not have a luck.

Then I tried to do it simple:

str = "[\w\s]+"
=> "[w ]+"

It escapes. Now how could string remains as it is and convert to a regexp object?

Answer

alony picture alony · Dec 28, 2011

Looks like here you need the initial string to be in single quotes (refer this page)

>> str = '[\w\s]+'
 => "[\\w\\s]+" 
>> Regexp.new str
 => /[\w\s]+/