From: MikkelFJ Date: 2003-02-21T22:21:48+09:00 Subject: Re: Regexp help: Parsing a CSV file "Tim Bates" wrote in message news:200302212243.48991.tim@bates.id.au... > 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... The following regular expression is used to break up properties separated by semicolon in a database connection string. It doesn handle xml style single and double quotes which allows embedded semicolon and embedded quotes of opposite type. I'm sure you can modify it to your purpose. Note the use of "*?" which prevents an expression from eating the remaining input. The syntax parsed is: '=' (';' '=' )* where value can optionally use single or double quote delimiters. The expression is actually used html client side Javascript, but I reckon that won't make a big impact. re = /[ \t\r\n]*(.*?)[ \t\r\n]*=[ \t\r\n]*(\'[^\']*\'|\"[^\"]*\"|[^;]*?)[ \t\r\n]*(;|$)/g Mikkel