stwissel
stwissel

Reputation: 20384

Regex for java.util.Scanner for csv files?

I want to read a CSV file using java.util.Scanner. First attempt looked promising:

 Scanner scanner = new Scanner(cFile);
 while (scanner.hasNextLine()) {
    String curLine = scanner.nextLine().trim();
    this.processRow(curLine);
 }

 private void processRow(String workString) {
     Scanner lineScanner = new Scanner(workString);
     lineScanner.useDelimiter(",");
     // .next goes through the elements
     lineScanner.next();
 } 

The challenge I'm facing is the line lineScanner.useDelimiter(",");. My CSV has commas inside the text and escaped double Quotes:

 Year,Value,Customer,NickName,Rank
 2012,45.56,T3456C,"Mike, \"The Gangster\"",1
 2012,1237.35,"A453F", Joe Armagendon,2
 2012,,X344,"Frank the weasel",3

Is there a regex that only filters the separators?

Upvotes: 1

Views: 780

Answers (1)

carlspring
carlspring

Reputation: 32597

As mentioned by nhahtdh, you should actually use a parser, as the way CSV works is a bit more complicated than the example.

There are many libraries for this out there. One I've used and forked is csvfile. It's pretty easy to use and does the job right.

Upvotes: 1

Related Questions