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.



514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
# File 'lib/ctioga2/utils.rb', line 514

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