Class: RegexpExamples::BackReferenceReplacer

Inherits:
Object
  • Object
show all
Defined in:
lib/regexp-examples/backreferences.rb

Overview

A helper class to fill-in backrefences AFTER the example(s) have been generated. In a nutshell, this works by doing the following:

  • Given a regex that contains a capute group and backreference, e.g. ‘/(a|b) 1/`

  • After generating examples, the backreference is tored as a placeholder: ‘[“a BACKREF-PLACEHOLDER-1”, “b BACKREF-PLACEHOLDER-1”]`

  • This class is used to fill in each placeholder accordingly: ‘[“a a”, “b b”]`

  • Also, beware of octal groups and cases where the backref invalidates the example!!

Constant Summary collapse

PLACEHOLDER_REGEX =

Named capture groups can only contain alphanumeric chars, and hyphens

Regexp.new(
  RegexpExamples::BackReferenceGroup::PLACEHOLDER_FORMAT % '([a-zA-Z0-9-]+)'
)

Instance Method Summary collapse

Instance Method Details

#substitute_backreferences(full_examples) ⇒ Object



16
17
18
19
20
21
22
23
24
# File 'lib/regexp-examples/backreferences.rb', line 16

def substitute_backreferences(full_examples)
  full_examples.map do |full_example|
    # For instance, one "full example" from /(a|(b)) \2/: "a __BACKREF-PLACEHOLDER-2__"
    # should be rejected because the backref (\2) does not exist
    catch(:backref_not_found) do
      substitute_backrefs_one_at_a_time(full_example)
    end
  end.compact
end