class RegexpExamples::BackReferenceReplacer

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

Constants

PLACEHOLDER_REGEX

Named capture groups can only contain alphanumeric chars, and hyphens

Public Instance Methods

substitute_backreferences(full_examples) click to toggle source
# 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

Private Instance Methods

find_backref_for(full_example, group_id) click to toggle source
# File lib/regexp-examples/backreferences.rb, line 38
def find_backref_for(full_example, group_id)
  full_example.all_subgroups.detect do |subgroup|
    subgroup.group_id == group_id
  end || octal_char_for(group_id)
end
octal_char_for(octal_chars) click to toggle source
# File lib/regexp-examples/backreferences.rb, line 44
def octal_char_for(octal_chars)
  # For octal characters in the range \00 - \177
  if octal_chars =~ /\A[01]?[0-7]{1,2}\z/ && octal_chars.length > 1
    Integer(octal_chars, 8).chr
  else
    throw :backref_not_found
  end
end
substitute_backrefs_one_at_a_time(full_example) click to toggle source
# File lib/regexp-examples/backreferences.rb, line 28
def substitute_backrefs_one_at_a_time(full_example)
  while full_example.match(PLACEHOLDER_REGEX)
    full_example.sub!(
      PLACEHOLDER_REGEX,
      find_backref_for(full_example, Regexp.last_match(1))
    )
  end
  full_example
end