Sha256: 8f5258043759cd5db61d09d722a9b339f19f1714c460fe3c3790adcf6ffabe7e
Contents?: true
Size: 1.06 KB
Versions: 2
Compression:
Stored size: 1.06 KB
Contents
module RegexpExamples class BackReferenceReplacer BackrefNotFound = Class.new(StandardError) 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, Regexp.last_match(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 private 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 def octal_char_for(octal_chars) # For octal characters in the range \10 - \177 if octal_chars =~ /\A[01]?[0-7]{1,2}\z/ && octal_chars.to_i >= 10 Integer(octal_chars, 8).chr else fail(BackrefNotFound) end end end end
Version data entries
2 entries across 2 versions & 1 rubygems
Version | Path |
---|---|
regexp-examples-1.1.3 | lib/regexp-examples/backreferences.rb |
regexp-examples-1.1.2 | lib/regexp-examples/backreferences.rb |