将字符串转换为正则表达式 ruby [英] Convert a string to regular expression ruby
问题描述
我需要将像 "/[\w\s]+/" 这样的字符串转换为正则表达式.
I need to convert string like "/[\w\s]+/" to regular expression.
"/[\w\s]+/" => /[\w\s]+/
我尝试使用不同的 Regexp
方法,例如:
I tried using different Regexp
methods like:
Regexp.new("/[\w\s]+/") =>//\/[w ]+\//
,类似Regexp.compile
和Regexp.escape
.但是他们都没有像我预期的那样返回.
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 ]+/
但运气不好.
然后我试着做的很简单:
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?
推荐答案
看起来这里你需要将初始字符串放在单引号中(参考 本页)
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]+/
这篇关于将字符串转换为正则表达式 ruby的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!