class ShellTest::RegexpEscape
RegexpEscape
is a subclass of regexp that escapes all but the text in a special escape sequence. This allows the creation of complex regexps to match, for instance, console output.
The RegexpEscape.escape
(or equivalently the quote) method does the work; all regexp-active characters are escaped except for characters enclosed by ‘:.’ and ‘.:’ delimiters.
RegexpEscape.escape('reg[exp]+ chars. are(quoted)') # => 'reg\[exp\]\+\ chars\.\ are\(quoted\)' RegexpEscape.escape('these are not: :.a(b*)c.:') # => 'these\ are\ not:\ a(b*)c'
All-period regexps are treated specially. A single period is translated to ‘.*?’ to lazily match anything on a single line. Multiple periods are translated to ‘(?:(?m).*?)’ to lazily match anything actoss multiple lines. Use the ‘.{n}’ notation to specify n arbitrary characters.
RegexpEscape.escape('a:...:b:....:c') # => 'a.*?b(?:(?m).*?)c' RegexpEscape.escape('a:..{1}.:b') # => 'a.{1}b'
RegexpEscape
instances are initialized using the escaped input string and return the original string upon to_s.
str = %q{ a multiline :...: example} r = RegexpEscape.new(str) r =~ %q{ a multiline matching example} # => true r !~ %q{ a failing multiline example} # => true r.to_s # => str
Constants
- ESCAPE_SEQUENCE
matches the escape sequence
Public Class Methods
Escapes regexp-active characters in str, except for character delimited by ‘:.’ and ‘.:’. See the class description for details.
# File lib/shell_test/regexp_escape.rb 51 def escape(str) 52 substituents = [] 53 str.scan(ESCAPE_SEQUENCE) do 54 regexp_str = $&[2...-2] 55 substituents << case regexp_str 56 when '.' 57 ".*?" 58 when /\A\.+\z/ 59 "(?:(?m).*?)" 60 else 61 regexp_str 62 end 63 end 64 substituents << "" 65 66 splits = str.split(ESCAPE_SEQUENCE).collect do |split| 67 super(split) 68 end 69 splits << "" if splits.empty? 70 71 splits.zip(substituents).to_a.flatten.join 72 end
Generates a new RegexpEscape
by escaping the str, using the same options as Regexp.
# File lib/shell_test/regexp_escape.rb 82 def initialize(str, *options) 83 super(RegexpEscape.escape(str), *options) 84 @original_str = str 85 end
Same as escape.
# File lib/shell_test/regexp_escape.rb 75 def quote(str) 76 escape(str) 77 end
Public Instance Methods
Returns the original string for self
# File lib/shell_test/regexp_escape.rb 88 def to_s 89 @original_str 90 end