Convert a string to regular expression ruby

RubyRegexStringRuby 1.9.3

Ruby Problem Overview


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?

Ruby Solutions


Solution 1 - Ruby

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]+/ 

Solution 2 - Ruby

To be clear

  /#{Regexp.quote(your_string_variable)}/

is working too

edit: wrapped your_string_variable in Regexp.quote, for correctness.

Solution 3 - Ruby

This method will safely escape all characters with special meaning:

/#{Regexp.quote(your_string)}/

For example, . will be escaped, since it's otherwise interpreted as 'any character'.

Remember to use a single-quoted string unless you want regular string interpolation to kick in, where backslash has a special meaning.

Solution 4 - Ruby

Using % notation:

%r{\w+}m => /\w+/m

or

regex_string = '\W+'
%r[#{regex_string}]

From help: > %r[ ] Interpolated Regexp (flags can appear after the closing > delimiter)

Solution 5 - Ruby

The gem to_regexp can do the work.

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

You also can use the modifier:

'/foo/i'.to_regexp => /foo/i

>Finally, you can be more lazy using :detect

'foo'.to_regexp(detect: true)     #=> /foo/
'foo\b'.to_regexp(detect: true)   #=> %r{foo\\b}
'/foo\b/'.to_regexp(detect: true) #=> %r{foo\b}
'foo\b/'.to_regexp(detect: true)  #=> %r{foo\\b/}

Solution 6 - Ruby

I just ran into this, where I literally need to change the string '/[\w\s]+/' to a regex in a transpiler. I used eval:

irb(main):001:0> eval( '/[\w\s]+/' )
=> /[\w\s]+/

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestioncmthakurView Question on Stackoverflow
Solution 1 - RubyalonyView Answer on Stackoverflow
Solution 2 - RubySergey GerasimovView Answer on Stackoverflow
Solution 3 - RubysandstromView Answer on Stackoverflow
Solution 4 - RubyBitOfUniverseView Answer on Stackoverflow
Solution 5 - RubyryanView Answer on Stackoverflow
Solution 6 - RubyJosephView Answer on Stackoverflow