125

我需要将“/[\w\s]+/”之类的字符串转换为正则表达式。

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

我尝试使用不同的Regexp方法,例如:

Regexp.new("/[\w\s]+/") => /\/[w ]+\//, 同样Regexp.compileRegexp.escape. 但他们都没有像我预期的那样返回。

此外,我尝试删除反斜杠:

Regexp.new("[\w\s]+") => /[w ]+/但没有运气。

然后我试着简单地做:

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

它逃脱了。现在字符串如何保持原样并转换为正则表达式对象?

4

5 回答 5

161

看起来在这里您需要将初始字符串放在单引号中(请参阅此页面

>> str = '[\w\s]+'
 => "[\\w\\s]+" 
>> Regexp.new str
 => /[\w\s]+/ 
于 2011-12-28T06:55:23.790 回答
144

要清楚

  /#{Regexp.quote(your_string_variable)}/

也在工作

编辑:为正确起见,将 your_string_variable 包装在 Regexp.quote 中。

于 2012-07-25T10:19:10.780 回答
37

此方法将安全地转义所有具有特殊含义的字符:

/#{Regexp.quote(your_string)}/

例如,.将被转义,因为它被解释为“任何字符”。

记住要使用单引号字符串,除非您希望使用常规字符串插值,其中反斜杠具有特殊含义。

于 2014-03-06T20:33:10.887 回答
10

使用 % 表示法:

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

或者

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

帮助

%r[ ] 插值正则表达式(标志可以出现在结束分隔符之后)

于 2014-12-15T11:39:46.327 回答
6

gem to_regexp可以完成这项工作。

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

您还可以使用修饰符:

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

最后,您可以使用 :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/}
于 2015-09-17T11:20:28.193 回答