Class: Linecook::Test::RegexpEscape
- Inherits:
-
Regexp
- Object
- Regexp
- Linecook::Test::RegexpEscape
- Defined in:
- lib/linecook/test/regexp_escape.rb
Overview
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'
In addition, all-period regexps are automatically upgraded to ‘.*?’; use the ‘.n’ notation to specify n arbitrary characters.
RegexpEscape.escape('_:..:_:...:_:....:') # => '_.*?_.*?_.*?'
RegexpEscape.escape(':..{1}.:') # => '.{1}'
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
Constant Summary collapse
- ESCAPE_SEQUENCE =
matches the escape sequence
/:\..*?\.:/
Class Method Summary collapse
-
.escape(str) ⇒ Object
Escapes regexp-active characters in str, except for character delimited by ‘:.’ and ‘.:’.
-
.quote(str) ⇒ Object
Same as escape.
Instance Method Summary collapse
-
#initialize(str, *options) ⇒ RegexpEscape
constructor
Generates a new RegexpEscape by escaping the str, using the same options as Regexp.
-
#to_s ⇒ Object
Returns the original string for self.
Constructor Details
#initialize(str, *options) ⇒ RegexpEscape
Generates a new RegexpEscape by escaping the str, using the same options as Regexp.
75 76 77 78 |
# File 'lib/linecook/test/regexp_escape.rb', line 75 def initialize(str, *) super(RegexpEscape.escape(str), *) @original_str = str end |
Class Method Details
.escape(str) ⇒ Object
Escapes regexp-active characters in str, except for character delimited by ‘:.’ and ‘.:’. See the class description for details.
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
# File 'lib/linecook/test/regexp_escape.rb', line 50 def escape(str) substituents = [] str.scan(ESCAPE_SEQUENCE) do regexp_str = $&[2...-2] regexp_str = ".*?" if regexp_str =~ /^\.*$/ substituents << regexp_str end substituents << "" splits = str.split(ESCAPE_SEQUENCE).collect do |split| super(split) end splits << "" if splits.empty? splits.zip(substituents).to_a.flatten.join end |
.quote(str) ⇒ Object
Same as escape.
68 69 70 |
# File 'lib/linecook/test/regexp_escape.rb', line 68 def quote(str) escape(str) end |
Instance Method Details
#to_s ⇒ Object
Returns the original string for self
81 82 83 |
# File 'lib/linecook/test/regexp_escape.rb', line 81 def to_s @original_str end |