Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS 

Partition a String based on a regex. Similar to String#split but matches are preserved.

I've create a handy Ruby String utility. It allows you to partition a String based on a regex (similar to String#split), but it preserves the matched sub-strings (unlike split). Here it is for anyone interested:

I also posted this code on my blog

   1  
   2  
   3  class String
   4  
   5    #partitions a string based on regex.  matches are included in results
   6    #ex. 'a b  c'.partition(/ +/) returns ['a', ' ', 'b', '  ', 'c']
   7    #ex. ' b '.partition(/ +/) returns [' ', 'b', ' ']
   8    def partition(regex)
   9      results = []
  10      s = StringScanner.new(self)
  11      last_pos = 0
  12      while(s.skip_until(regex))
  13        matched_size = s.matched_size
  14        pos = s.pos
  15        #add the non-delimiter string if it exists (it may not if the string starts with a delimiter)
  16        results << self[last_pos ... pos - matched_size] if last_pos < pos - matched_size
  17        #add the delimiter
  18        results << self[pos - matched_size ... pos]
  19        #update the last_pos to the current pos
  20        last_pos = pos
  21      end
  22      #add the last non-delimiter string if one exists after the last delimiter.  It would not have
  23      #been added since s.skip_until would have returned nil
  24      results << self[last_pos ... self.length] if last_pos < self.length
  25      results
  26    end
  27  end
« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS