From: Gavin Kistner Date: 2005-09-28T14:00:37+09:00 Subject: Re: Splitting a string with escapable separator? On Sep 27, 2005, at 5:46 PM, Michael Schuerig wrote: > I'm trying to come up with an *elegant* way to split a string into an > array at a separator with the additional feature that the separators > can be escaped. It should work like this > > "Hello\, World,Hi".split_escapable(',' '\') > # => ["Hello, World", "Hi"] > > Through a number of permutations with regexps, scan and the rest of > the > family, I was unable to find a solution. Your above example is missing a couple of \, but I assume I know what you meant. Is the following elegant or not? class String def split_escapable( separator, escape_char=nil ) results = [] re = /(.+?)(?:#{escape_char ? "([^\\#{escape_char}])" : ''}# {separator}|$)/ self.scan( re ){ |str,last_char| results << str + last_char.to_s } results end end p "Hello\\, World,Hi".split_escapable( ',', '\\' ) #=> ["Hello\\, World", "Hi"] Note that the above does not account for the case of: Hello \\,World (where an escaped backslash is intended to end the first entry) but if that was important, that's just a matter of a bit of odd/even backslash counting. Something like (untested): re = /(.+?)(?:#{escape_char ? "([^\\#{escape_char}](\\#{escape_char}\ \#{escape_char})*)" : ''}#{separator}|$)/