将字符串中的正则表达式转换为 ruby​​ 中的正则表达式对象

编程入门 行业动态 更新时间:2024-10-27 00:29:15
本文介绍了将字符串中的正则表达式转换为 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

来源在 github/seamusabshere/to_regexp

更多推荐

将字符串中的正则表达式转换为 ruby​​ 中的正则表达式对象

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

发布评论

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

>www.elefans.com

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