Module: Enumpath::RegexpParser

Defined in:
lib/enumpath/regexp_parser.rb

Overview

Parses the regular expression literals that a filter expression accepts (/pattern/flags and %r{pattern}flags) into a Regexp. The pattern is passed to Regexp.new as text and never evaluated as Ruby code, so #{...} in it stays plain text.

Constant Summary collapse

LITERAL =
%r{\A(?:/(.*)/|%r\{(.*)\})([a-z]*)\z}m.freeze
FLAGS =
{ 'i' => Regexp::IGNORECASE, 'm' => Regexp::MULTILINE, 'x' => Regexp::EXTENDED, 'n' => Regexp::NOENCODING,
'u' => 0 }.freeze

Class Method Summary collapse

Class Method Details

.parse(string) ⇒ Regexp?

Returns the regular expression, or nil if the string is not a regular expression literal (this includes flags other than i, m, x, n and u).

Parameters:

  • string (String) —

    an operand from a path

Returns:

  • (Regexp, nil) —

    the regular expression, or nil if the string is not a regular expression literal (this includes flags other than i, m, x, n and u)

Raises:

  • (RegexpError) —

    if the string is a regular expression literal whose pattern is not valid



17
18
19
20
21
22
23
24
25
26
27
# File 'lib/enumpath/regexp_parser.rb', line 17

def parse(string)
  match = LITERAL.match(string)
  return unless match

  options = options_for(match[3])
  return if options.nil?

  # An escaped delimiter and a plain delimiter mean the same inside a pattern
  pattern = (match[1] || match[2]).gsub('\\/', '/')
  Regexp.new(pattern, options)
end