[Note: parts of this message were removed to make it a legal post.]
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
Josh said:
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 =<<ENDOFSTRING
hello rEG
world exP
ENDOFSTRING
...nor when there is more than one flag.