class String

Public Instance Methods

split_at_toplevel(regexp) click to toggle source

Splits a string into substrings at the given regexp, but only if the splitting occurs at top-level with respect to parentheses.

# File lib/ctioga2/utils.rb, line 749
def split_at_toplevel(regexp)
  # Groups
  grps = {} 
  
  sz = 0
  s = self.dup
  while true
    s.gsub!(/\([^()]+\)/) do |x|
      idx = grps.size
      rep = "__#{idx}__"
      grps[rep] = x
      rep
    end
    if sz == grps.size
      break
    else
      sz = grps.size
    end
  end
  
  splitted = s.split(regexp)
  
  while grps.size > 0
    for s in splitted
      s.gsub!(/__\d+__/) do |x|
        rep = grps[x]
        grps.delete(x)
        rep
      end
    end
  end
  return splitted
end