简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM