Class: Tap::Test::RegexpEscape
- Defined in:
- lib/tap/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) ⇒ RegexpEscape
constructor
A new instance of RegexpEscape.
-
#to_s ⇒ Object
Returns the original string for self.
Constructor Details
#initialize(str) ⇒ RegexpEscape
Returns a new instance of RegexpEscape.
76 77 78 79 |
# File 'lib/tap/test/regexp_escape.rb', line 76 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.
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 |
# File 'lib/tap/test/regexp_escape.rb', line 53 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.
71 72 73 |
# File 'lib/tap/test/regexp_escape.rb', line 71 def quote(str) escape(str) end |
Instance Method Details
#to_s ⇒ Object
Returns the original string for self
82 83 84 |
# File 'lib/tap/test/regexp_escape.rb', line 82 def to_s @original_str end |