Sha256: cb7b13bb612faa3c555500e91df0e1dfb7b8d630f2f4ff5a6cd3ce1a9dc70f37

Contents?: true

Size: 1.46 KB

Versions: 1

Compression:

Stored size: 1.46 KB

Contents

# encoding: utf-8
module ToRegexp
  module Regexp
    def to_regexp
      self
    end
  end
  
  module String
    REGEXP_DELIMITERS = {
      '%r{' => '}',
      '/' => '/',
    }

    def to_regexp
      if args = as_regexp
        ::Regexp.new *args
      end
    end
    
    def as_regexp
      str = self.dup
      unless delim_set = REGEXP_DELIMITERS.detect { |k, v| str.start_with? k }
        # no starting delimiter found
        return
      end
      delim_start, delim_end = delim_set.map { |delim| ::Regexp.escape delim }
      /\A#{delim_start}(.*)#{delim_end}([^#{delim_end}]*)\z/u =~ str.strip
      content = $1
      options = $2
      unless content.is_a?(::String) and options.is_a?(::String)
        # maybe a missing end delimiter?
        return
      end
      content.gsub! '\\/', '/'
      ignore_case = options.include?('i') ? ::Regexp::IGNORECASE : 0
      multiline = options.include?('m') ? ::Regexp::MULTILINE : 0
      extended = options.include?('x') ? ::Regexp::EXTENDED : 0
      # 'n', 'N' = none, 'e', 'E' = EUC, 's', 'S' = SJIS, 'u', 'U' = UTF-8
      lang = options.scan(/[nesu]/i).join.downcase
      if ::RUBY_VERSION > '1.9' and lang.include?('u')
        lang.gsub! 'u', ''
      end
      if lang.empty?
        [ content, (ignore_case|multiline|extended) ]
      else
        [ content, (ignore_case|multiline|extended), lang ]
      end
    end
  end

end

::String.send :include, ::ToRegexp::String
::Regexp.send :include, ::ToRegexp::Regexp

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
to_regexp-0.0.3 lib/to_regexp.rb