# TITLE: # Matchset # # DESCRIPTION: # Matchdata methods to produces a hierachical list of a match result. # This also includes Regexp#arity. # # AUTHORS: # - Thomas Sawyer # class MatchData # TODO Is MatchData#match really worth having? It's kind of confusing w/ Regexp#match. # Return the primary match string. This is equivalent to +md[0]+. # # md = /123/.match "123456" # md.match #=> "123" # def match self[0] end # Returns [ pre_match, matchtree, post_match ]. (see matchtree) # # md = /(bb)(cc(dd))(ee)/.match "XXaabbccddeeffXX" # md.to_a #=> ["XXaabbccddeeffXX", "bb", "ccdd", "dd", "ee"] # md.matchset #=> ["XXaa", [["bb"], ["cc", ["dd"]], "ee"], "ffXX"] # def matchset [pre_match, matchtree, post_match] end # An alternate to #to_a which returns the matches in # order corresponding with the regular expression. # # md = /(bb)(cc(dd))(ee)/.match "XXaabbccddeeffXX" # md.to_a #=> ["XXaabbccddeeffXX", "bb", "ccdd", "dd", "ee"] # md.matchtree #=> [["bb"], ["cc", ["dd"]], "ee"] # def matchtree(index=0) ret=[] b, e=self.begin(index), self.end(index) while (index+=1)<=length if index==length || (bi=self.begin(index))>=e # we are finished, if something is left, then add it ret << string[b, e-b] if e>b break else if bi>=b ret << string[b, bi-b] if bi>b ret << matchtree(index) b=self.end(index) end end end return ret end end # _____ _ # |_ _|__ ___| |_ # | |/ _ \/ __| __| # | | __/\__ \ |_ # |_|\___||___/\__| # =begin test require 'test/unit' class TestMatchData < Test::Unit::TestCase def test_match md = /X(a)(b)(c)X/.match("YXabcXY") assert_equal( "XabcX", md.match ) end def test_matchtree_01 md = /(bb)(cc(dd))(ee)/.match "XXaabbccddeeffXX" assert_equal( [["bb"], ["cc", ["dd"]], ["ee"]] , md.matchtree ) end def test_matchtree_02 md = /(bb)c(c(dd))(ee)/.match "XXaabbccddeeffXX" assert_equal( [["bb"], "c", ["c", ["dd"]], ["ee"]] , md.matchtree ) end def test_matchset md = /(bb)(cc(dd))(ee)/.match "XXaabbccddeeffXX" assert_equal( ["XXaa", [["bb"], ["cc", ["dd"]], ["ee"]], "ffXX"] , md.matchset ) end end =end