From: Christian Rishoj Date: 2003-02-21T21:41:29+09:00 Subject: Re: Regexp help: Parsing a CSV file On Fri, 21 Feb 2003, Tim Bates wrote: > I've dumped a CSV (comma separated values) file from Excel, and I want to > parse it into cels within my Ruby script. Easy enough, you say: > line.split(',') > But it's a little more complicated than that - see, if the cel has a comma in > it, it gets surrounded in quotes. If a cel has a quote in it, it's surrounded > by quotes and doubled, eg: > Test Te,st Te"st > becomes > Test,"Te,st","Te""st" > Now to use String#split, I would have to write a regexp that will match a > comma, provided that comma is preceeded by an even number of quotes. BUT, I > don't want the regexp to match the quotes themselves, just the comma. I can't > figure this one out... line.split(',').collect do |e| if e[0] == '"' && e[e.length - 1] == '"' e[1...e.length].gsub('""', '"') else e end end - Christian