Convert a string to regular expression ruby

吃可爱长大的小学妹 提交于 2019-11-28 16:35:36

问题


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?


回答1:


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



回答2:


To be clear

  /#{Regexp.quote(your_string_variable)}/

is working too

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




回答3:


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.




回答4:


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)




回答5:


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/}


来源:https://stackoverflow.com/questions/8652715/convert-a-string-to-regular-expression-ruby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!