Convert regex into string to regex object in ruby

I accept the regular expression as input from the user and matching the values ​​with this regular expression. But the problem I have is that the input I get is a string. for example "/abc|def/i" And I cannot convert it to a regular expression object. If he tries Regexp.new(string) he avoids all the characters, so I get something like /\/abc|def\/i/

I managed to capture the part between the slash using another regular expression and build a regexp object with it. In the above example, I capture "abc|def" , and when I do Regexp.new("abc|def") , I get /abc|def/ , which I wanted, but I need to add regexp options too (for example, " i "in the above example) in string to the regexp ruby ​​object.

How can I achieve this?

In addition, there should be an easier way to achieve all this. Any help would be greatly appreciated.

+2
source share
4 answers

You can learn to_regexp gem ; it does not use eval and this will allow you to do this:

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

Source https://github.com/seamusabshere/to_regexp

+5
source

Here is a quick way to do this /#{my_string_pattern}/

No magic required

+5
source

Just for fun ... enjoy:

 class Regexp def self.parse(s) optmap = { "i" => Regexp::IGNORECASE, "x" => Regexp::EXTENDED, "m" => Regexp::MULTILINE } match = s.match(/\/(.*)\/(.*)/) or raise "Invalid regexp string" pat = match.captures[0] opt_str = match.captures[1] opts = opt_str.split(//).map { |c| optmap[c] }.reduce { |x, n| x | n } Regexp.new(pat, opts) end end # because you aren't hacking Ruby until you've added a method to String... class String def to_regex Regexp.parse(self) end end 

It works too!

+4
source

As you said, I believe your method may be a way to handle this. You can clean it up a bit by doing something like this ...

 class String def to_regexp(case_insensitive = false) str = self[\/(.*)\/,1] Regexp.new(str, case_insensitive) end end 

This is just one way to clear it and make the functionality inherent in Strings so you don't have to worry about it.

0
source

Source: https://habr.com/ru/post/915399/


All Articles