Created
April 18, 2011 22:43
-
-
Save seamusabshere/926425 to your computer and use it in GitHub Desktop.
String#to_regexp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# | |
# 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