Partition A String Based On A Regex. Similar To String#split But Matches Are Preserved.
Join the DZone community and get the full member experience.Join For Free
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
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