将字符串转换为正则表达式 ruby

编程入门 行业动态 更新时间:2024-10-27 12:26:57
本文介绍了将字符串转换为正则表达式 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 ]+\//,类似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

本文发布于:2023-11-05 09:03:16,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1560426.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:转换为   字符串   正则表达式   ruby

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!