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.



749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
# 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