Class: RegexpExamples::BackReferenceReplacer

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

Constant Summary collapse

BackrefNotFound =
Class.new(StandardError)

Instance Method Summary collapse

Instance Method Details

#substitute_backreferences(full_examples) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
16
17
18
# File 'lib/regexp-examples/backreferences.rb', line 5

def substitute_backreferences(full_examples)
  full_examples.map do |full_example|
    begin
      while full_example.match(/__(\w+?)__/)
        full_example.sub!(/__(\w+?)__/, find_backref_for(full_example, $1))
      end
      full_example
    rescue BackrefNotFound
      # For instance, one "full example" from /(a|(b)) \2/: "a __2__"
      # should be rejected because the backref (\2) does not exist
      nil
    end
  end.compact
end