Class: String

Inherits:
Object
  • Object
show all
Defined in:
lib/ctioga2/utils.rb

Instance Method Summary collapse

Instance Method Details

#split_at_toplevel(regexp) ⇒ Object

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



704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
# File 'lib/ctioga2/utils.rb', line 704

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