Class: MatchData

Inherits:
Object show all
Defined in:
lib/core/facets/matchdata/matchset.rb

Instance Method Summary collapse

Instance Method Details

#matchObject

Return the primary match string. This is equivalent to md[0].

md = /123/.match "123456"
md.match  #=> "123"

TODO: Is MatchData#match really worth having? It's kind of confusing w/ Regexp#match.

CREDIT: Trans


12
13
14
# File 'lib/core/facets/matchdata/matchset.rb', line 12

def match
  self[0]
end

#matchsetObject

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"]

CREDIT: Trans


24
25
26
# File 'lib/core/facets/matchdata/matchset.rb', line 24

def matchset
   [pre_match, matchtree, post_match]
end

#matchtree(index = 0) ⇒ Object

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"]

CREDIT: Trans


37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/core/facets/matchdata/matchset.rb', line 37

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