lib/regexp-examples/groups.rb in regexp-examples-0.2.1 vs lib/regexp-examples/groups.rb in regexp-examples-0.2.2

- old
+ new

@@ -1,12 +1,37 @@ module RegexpExamples + # All Group#result methods return an array of GroupResult objects + # The key objective here is to keep track of all capture groups, in order + # to fill in backreferences + class GroupResult < String + attr_reader :group_id, :subgroups + def initialize(result, group_id = nil, subgroups = []) + @group_id = group_id + @subgroups = subgroups + if result.respond_to?(:group_id) + @subgroups = result.all_subgroups + end + super(result) + end + + def all_subgroups + [self, subgroups].flatten.reject { |subgroup| subgroup.group_id.nil? } + end + + # Overridden in order to preserve the @group_id and @subgroups + # Used by BaseGroup (which, in turn, is used by all Group objects) + def *(int) + self.class.new(super.to_s, group_id, subgroups) + end + end + class SingleCharGroup def initialize(char) @char = char end def result - [@char] + [GroupResult.new(@char)] end end class CharGroup def initialize(chars) @@ -50,21 +75,21 @@ end end end def result - if @negative - CharSets::Any - @chars - else - @chars + (@negative ? (CharSets::Any - @chars) : @chars).map do |result| + GroupResult.new(result) end end end class DotGroup def result - CharSets::Any + CharSets::Any.map do |result| + GroupResult.new(result) + end end end class MultiGroup attr_reader :group_id @@ -77,12 +102,11 @@ # and adds the filled group of each result to # itself def result strings = @groups.map {|repeater| repeater.result} RegexpExamples::permutations_of_strings(strings).map do |result| - subgroups = result.respond_to?(:group_id) ? result.all_subgroups : [] - group_id ? CaptureGroupResult.new(group_id, subgroups, result) : result + GroupResult.new(result, group_id) end end end class MultiGroupEnd @@ -99,21 +123,23 @@ RegexpExamples::permutations_of_strings([repeater.result]) end right_result = @right_repeaters.map do |repeater| RegexpExamples::permutations_of_strings([repeater.result]) end - left_result.concat(right_result).flatten.uniq + left_result.concat(right_result).flatten.uniq.map do |result| + GroupResult.new(result) + end end end class BackReferenceGroup attr_reader :id def initialize(id) @id = id end def result - ["__#{@id}__"] + [ GroupResult.new("__#{@id}__") ] end end end