DZone 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
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 <a href="http://doubleplusdarwin.blogspot.com/2005/12/ive-create-handy-ruby-string-utility.html">code</a> on my blog
class String #partitions a string based on regex. matches are included in results #ex. 'a b c'.partition(/ +/) returns ['a', ' ', 'b', ' ', 'c'] #ex. ' b '.partition(/ +/) returns [' ', 'b', ' '] def partition(regex) results =  s = StringScanner.new(self) last_pos = 0 while(s.skip_until(regex)) matched_size = s.matched_size pos = s.pos #add the non-delimiter string if it exists (it may not if the string starts with a delimiter) results << self[last_pos ... pos - matched_size] if last_pos < pos - matched_size #add the delimiter results << self[pos - matched_size ... pos] #update the last_pos to the current pos last_pos = pos end #add the last non-delimiter string if one exists after the last delimiter. It would not have #been added since s.skip_until would have returned nil results << self[last_pos ... self.length] if last_pos < self.length results end end