I also posted this code 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
p " b ".split(/(\w)/)