Partition a String based on a regex. Similar to String#split but matches are preserved.
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