Skip to content

Instantly share code, notes, and snippets.

@seamusabshere
Created April 18, 2011 22:43
Show Gist options
  • Save seamusabshere/926425 to your computer and use it in GitHub Desktop.
Save seamusabshere/926425 to your computer and use it in GitHub Desktop.
String#to_regexp
#
# DEPRECATED - and probably broken
# use to_regexp gem instead
# https://github.com/seamusabshere/to_regexp
# https://rubygems.org/gems/to_regexp
#
class String
REGEXP_DELIMITERS = {
'%r{' => '}',
'/' => '/'
}
def to_regexp
str = self.dup
delim_start, delim_end = REGEXP_DELIMITERS.detect { |k, v| str.start_with? k }.map { |delim| ::Regexp.escape delim }
%r{\A#{delim_start}(.*)#{delim_end}([^#{delim_end}]*)\z} =~ str.strip
content = $1
options = $2
content.gsub! '\\/', '/'
ignore_case = options.include?('i') ? ::Regexp::IGNORECASE : nil
multiline = options.include?('m') ? ::Regexp::MULTILINE : nil
extended = options.include?('x') ? ::Regexp::EXTENDED : nil
::Regexp.new content, (ignore_case|multiline|extended)
end
end
class Regexp
def to_regexp
dup
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment