From: Josh Cheek Date: 2009-08-21T21:06:58+09:00 Subject: Re: How to convert string "/regexp/i" to /regexp/i - ? --000e0cd4b38250afc70471a5b416 Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: 7bit Sorry, it gave me what I expected, and Ruby is usually intuitive, so I thought I got it right. This class, however, is not. I had to learn some of it's internal logic to figure it out. (they define constants for each flag, these constants are integers, you then have to add the values of the constants of all the flags together to get the new options value) class String return nil unless self.strip.match(/\A\/(.*)\/(.*)\Z/mx) regexp , flags = $1 , $2 return nil if !regexp || flags =~ /[^xim]/m x = /x/.match(flags) && Regexp::EXTENDED i = /i/.match(flags) && Regexp::IGNORECASE m = /m/.match(flags) && Regexp::MULTILINE Regexp.new regexp , [x,i,m].inject(0){|a,f| f ? a+f : a } end end #fail cases "regexp".to_r # => nil "regexp/i".to_r # => nil "/regexp/mk".to_r # => nil <<-ENDOFSTRING.to_r # => nil hello rEG world exP ENDOFSTRING "/regexp/mk hello rEG world exP".to_r # => nil #pass cases "/reg/".to_r # => /reg/ " /reg/x ".to_r # => /reg/x "/reg.*?exp/m".to_r # => /reg.*?exp/m "/regexp/x".to_r # => /regexp/x "/abc def ghi/xi".to_r # => /abc # def # ghi/ix "//".to_r # => // "/abc/i".to_r # => /abc/i "/abc/x".to_r # => /abc/x "/abc/m".to_r # => /abc/m "/abc/ix".to_r # => /abc/ix "/abc/im".to_r # => /abc/mi "/abc/xm".to_r # => /abc/mx "/abc/ixm".to_r # => /abc/mix "/abc/mxi".to_r # => /abc/mix On Fri, Aug 21, 2009 at 5:27 AM, 7stud -- wrote: > Josh Cheek wrote: > > class String > > def to_r > > Regexp.new(*strip.match(/\/(.*)\/(.*)/)[1,2]) > > end > > end > > > > "/regexp/i".to_r # => /regexp/i > > > > Doesn't work in this case: > > str = "/reg.*?exp/m" > > test_str =< hello rEG > world exP > ENDOFSTRING > > ...nor when there is more than one flag. > > > > > > -- > Posted via http://www.ruby-forum.com/. > > --000e0cd4b38250afc70471a5b416--