From: Han Holl Date: 2005-09-29T19:18:35+09:00 Subject: Re: Splitting a string with escapable separator? ------=_Part_1590_9868449.1127989112255 Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: quoted-printable Content-Disposition: inline On 9/28/05, 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(',' '\') > # =3D> ["Hello, World", "Hi"] > > None of the offerings so far had support for the second argument for split. The following is probably quite efficent if the chance of an occurrence of an escaped character is low. (I haven't benchmarked anything, though). Also, it's not suitable for binar= y strings. class String def split_escapable(separator, escape_char, *args) istr =3D dup impossible =3D "\x01" replace =3D "#{escape_char}#{separator}" changed =3D istr.gsub!(replace, impossible) fields =3D istr.split(separator, *args) if changed fields.each do |f| f.gsub!(impossible, separator) end end fields end end a =3D "Hello\\, World,Hi" puts a.split_escapable( ',', '\\' ) Cheers, Han Holl ------=_Part_1590_9868449.1127989112255--