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

Snippets has posted 5883 posts at DZone. View Full User Profile

Partition A String Based On A Regex. Similar To String#split But Matches Are Preserved.

  • submit to reddit
        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="">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 =
    last_pos = 0
      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
    #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


Snippets Manager replied on Mon, 2012/05/07 - 1:17pm

p "a b c".split(/( )/) p " b ".split(/(\w)/)