From: Brian Candler Date: 2012-01-22T06:12:35+09:00 Subject: Re: How to convert string "/regexp/i" to /regexp/i - ? Ben Giddings wrote in post #844686: > If the strings are provided by an untrusted source, don't use any > solution that uses eval(). Yes. > Instead, use a solution that recognizes the string contains a regexp > and then uses a regexp constructor after pulling the relevant data out > of the string. Something along the lines of: > > def parse_input(str) > if md = %r{^/(.*)+/(.*)*$}.match(str) Nice try, but that regexp isn't safe. I think Ruby's design decision here was a bad one. In Ruby, you need \A to match only at the start of string, and \z to match only at the end of string (whereas you might expect ^ and $ to mean that) Also, I'd suggest that repeated capture groups are a bit confusing, e.g. where you write (.*)+ when (.*) by itself would be fine. Because * is greedy, .* will capture as much as possible so the + will only repeat once. Anyway, here's a trick for handling the flags: note that /foo/i can be represented as (?i:foo) raise "Invalid regexp" unless %r{\A/(.*)/([mix]*)\z} =~ str Regexp.new("(?#{$2}:#{$1})") -- Posted via http://www.ruby-forum.com/.