将字符串中的正则表达式转换为 ruby​​ 中的正则表达式对象 [英] Convert a regular expression in a string to a regexp object in ruby

查看:38
本文介绍了将字符串中的正则表达式转换为 ruby​​ 中的正则表达式对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将正则表达式作为用户的输入,并将值与该正则表达式进行匹配.但是,我遇到的问题是我收到的输入是一个字符串.例如"/abc|def/i"而且我无法将其转换为正则表达式对象.如果它尝试 Regexp.new(string)它转义所有字符,所以我得到类似 /\/abc|def\/i/

I take a regular expression as an input from the user and match values against that regex. But, the problem i have is that the input i receive is a string. e.g. "/abc|def/i" And i am not able to convert it to a regex object. If it try Regexp.new(string) it escapes all the characters so i get something like /\/abc|def\/i/

我能够使用另一个正则表达式捕获正斜杠之间的部分,并使用它构建一个正则表达式对象.对于上面的例子,我捕获 "abc|def" 并且当我执行 Regexp.new("abc|def") 我得到 /abc|def/ 这是我想要的,但我需要一种方法来将字符串中的正则表达式选项(例如上面示例中的i")添加到 ruby​​ 正则表达式对象.

I was able to capture the part between the forward slashes using another regex and build a regexp object using it. For the above example, i capture "abc|def" and when i do Regexp.new("abc|def") i get /abc|def/ which is what i wanted but i need a way to also add the regexp options(e.g. 'i' in the above example) in the string to the ruby regexp object.

我怎样才能做到这一点???

How can i achieve this ???

此外,必须有一种更简单的方法来实现这一切.任何帮助将不胜感激.

Also, there must be a easier way to achieve all of this. Any help would be greatly appreciated.

推荐答案

您可能会考虑使用 to_regexp gem;它不使用 eval 并且它允许你这样做:

You might look into using the to_regexp gem; it doesn't use eval and it will allow you to do this:

 "/(abc|def)/i".to_regexp
 # => /(abc|def)/i

来源在 https://github.com/seamusabshere/to_regexp

这篇关于将字符串中的正则表达式转换为 ruby​​ 中的正则表达式对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆