Never been to DZone Snippets before?

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. (See related posts)

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

Comments on this post

nemostultae posts on Dec 29, 2005 at 20:07
p "a b c".split(/( )/)
p " b ".split(/(\w)/)

You need to create an account or log in to post comments to this site.


Click here to browse all 4861 code snippets

Related Posts