Module: ToRegexp::String
- Defined in:
- lib/to_regexp.rb
Constant Summary collapse
- INLINE_OPTIONS =
/[imxnesu]*/- REGEXP_DELIMITERS =
{ '%r{' => '}', '/' => '/', }
Class Method Summary collapse
Instance Method Summary collapse
-
#as_regexp(options = {}) ⇒ Object
Return arguments that can be passed to
Regexp.new. -
#to_regexp(options = {}) ⇒ Object
Get a regexp back.
Class Method Details
.literal?(str) ⇒ Boolean
11 12 13 |
# File 'lib/to_regexp.rb', line 11 def literal?(str) REGEXP_DELIMITERS.none? { |s, e| str.start_with?(s) and str =~ /#{e}#{INLINE_OPTIONS}\z/ } end |
Instance Method Details
#as_regexp(options = {}) ⇒ Object
Return arguments that can be passed to Regexp.new
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 |
# File 'lib/to_regexp.rb', line 41 def as_regexp( = {}) unless .is_a?(::Hash) raise ::ArgumentError, "[to_regexp] Options must be a Hash" end str = self return if [:detect] and str == '' if [:literal] or ([:detect] and ToRegexp::String.literal?(str)) content = ::Regexp.escape str elsif delim_set = REGEXP_DELIMITERS.detect { |k, _| str.start_with?(k) } delim_start, delim_end = delim_set /\A#{delim_start}(.*)#{delim_end}(#{INLINE_OPTIONS})\z/u =~ str content = $1 = $2 return unless content.is_a?(::String) content.gsub! '\\/', '/' if [:ignore_case] = true if .include?('i') [:multiline] = true if .include?('m') [:extended] = true if .include?('x') # 'n', 'N' = none, 'e', 'E' = EUC, 's', 'S' = SJIS, 'u', 'U' = UTF-8 [:lang] = .scan(/[nesu]/i).join.downcase end else return end ignore_case = [:ignore_case] ? ::Regexp::IGNORECASE : 0 multiline = [:multiline] ? ::Regexp::MULTILINE : 0 extended = [:extended] ? ::Regexp::EXTENDED : 0 lang = [:lang] || '' if ::RUBY_VERSION > '1.9' and lang.include?('u') lang = lang.delete 'u' end if lang.empty? [ content, (ignore_case|multiline|extended) ] else [ content, (ignore_case|multiline|extended), lang ] end end |
#to_regexp(options = {}) ⇒ Object
Get a regexp back
Without :literal or :detect, "foo".to_regexp will return nil.
33 34 35 36 37 |
# File 'lib/to_regexp.rb', line 33 def to_regexp( = {}) if args = as_regexp() ::Regexp.new *args end end |