Module: Corefines::String::ToRe

Defined in:
lib/corefines/string.rb

Instance Method Summary collapse

Instance Method Details

#to_re(opts = {}) ⇒ Regexp?

Note:

This method was renamed from to_regexp to to_re due to bug in MRI, see #11117.

Returns a regular expression represented by this string.

Examples:

'/^foo/'.to_re                  # => /^foo/
'/foo/i'.to_re                  # => /foo/i
'foo'.to_re                     # => nil

'foo'.to_re(literal: true)      # => /foo/
'^foo*'.to_re(literal: true)    # => /\^foo\*/

'/foo/'.to_re(detect: true)     # => /foo/
'$foo/'.to_re(detect: true)     # => /\$foo\//
''.to_re(detect: true)          # => nil

'/foo/'.to_re(multiline: true)  # => /foo/m

Parameters:

  • opts (Hash) (defaults to: {})

    options

Options Hash (opts):

  • :literal (Boolean)

    treat meta characters and other regexp codes as just a text. Never returns nil. (default: false)

  • :detect (Boolean)

    if string starts and ends with a slash, treat it as a regexp, otherwise interpret it literally. (default: false)

  • :ignore_case (Boolean)

    same as /foo/i. (default: false)

  • :multiline (Boolean)

    same as /foo/m. (default: false)

  • :extended (Boolean)

    same as /foo/x. (default: false)

Returns:

  • (Regexp, nil)

    a regexp, or nil if :literal is not set or false and this string doesn't represent a valid regexp or is empty.


443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
# File 'lib/corefines/string.rb', line 443

module ToRe
  refine ::String do
    def to_re(opts = {})

      if opts[:literal]
        content = ::Regexp.escape(self)

      elsif self =~ %r{\A/(.*)/([imxnesu]*)\z}
        content, inline_opts = $1, $2
        content.gsub! '\\/', '/'

        { ignore_case: 'i', multiline: 'm', extended: 'x' }.each do |k, v|
          opts[k] ||= inline_opts.include? v
        end if inline_opts

      elsif opts[:detect] && !self.empty?
        content = ::Regexp.escape(self)
      else
        return
      end

      options = 0
      options |= ::Regexp::IGNORECASE if opts[:ignore_case]
      options |= ::Regexp::MULTILINE if opts[:multiline]
      options |= ::Regexp::EXTENDED if opts[:extended]

      ::Regexp.new(content, options)
    end
  end
end