我将正则表达式作为用户的输入,并将值与该正则表达式进行匹配.但是,我遇到的问题是我收到的输入是一个字符串.例如"/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 中的正则表达式对象
发布评论