0

I am trying to generate a CSV file after reading data from database. Now individual data can contain comma, single quote and double quotes.

Please advice me How can I handle that situation with the help of regular expression.

stema
  • 90,351
  • 20
  • 107
  • 135
  • possible duplicate of [csv api for java](http://stackoverflow.com/questions/101100/csv-api-for-java) – Mat Sep 16 '11 at 12:20
  • If one of the answers you got solved your problem, please accept it by clicking on the check mark. – andronikus Sep 27 '11 at 03:08

4 Answers4

2

Can you use a different separator for your CSV file? A pipe ( | ) perhaps?

Mark Pope
  • 11,244
  • 10
  • 49
  • 59
2

The easiest is to put quotation marks around all data, then you can have commas, quotation marks (souble quotes) and line breaks in the data without problem.

You only have to escape quotation marks in the data by replacing them with double quotation marks. You don't need a regular expression for that, just use a regular string replace.

Apostrophes (single quotes) doesn't have any special meaning in the CSV format, so they are not a problem.

Guffa
  • 687,336
  • 108
  • 737
  • 1,005
1

Well, the commas aren't really a problem, because they're enclosed in double quotes to signify a string. Same for the single quotes. The only thing you need to do is escape the double quotes. Here's an example:

Joe said "Go home now and don't be late. I'd get in 'big' trouble."

would become

"Joe said ""Go home now and don't be late. I'd get in 'big' trouble."""

mamboking
  • 4,559
  • 23
  • 27
0

Writing a functional CSV parser is not a trivial task, even though the data format is so simple. Instead, consider using a library for this. I've used the CSVReader library, and it's very easy. The site includes code samples as well.

andronikus
  • 4,125
  • 2
  • 29
  • 46