我需要将像 "/[\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 ]+\//,类似Regexppile 和Regexp.escape.但是他们都没有像我预期的那样返回.
Regexp.new("/[\w\s]+/") => /\/[w ]+\//, similarly Regexppile 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
发布评论