From: William James Date: 2005-09-28T19:26:44+09:00 Subject: Re: Splitting a string with escapable separator? 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. I could parse the given string > myself, going though it character by character, but I'd prefer a less > pedestrian approach. class String def split_escapable( splitter, escaper ) escaper = escaper*2 if escaper=='\\' re = %r{ \G # Make sure at least 1 character remains. (?= . ) ( (?: [^#{ splitter }#{ escaper }] | (?: #{ escaper } . ) ) * ) (?: #{ splitter } | \Z ) }xm scan( re ).map{|x| x.first.gsub( /#{escaper}(.)/, '\1' ) } end end s = <