简体   繁体   English

用于csv文件的java.util.Scanner的正则表达式?

[英]Regex for java.util.Scanner for csv files?

I want to read a CSV file using java.util.Scanner . 我想使用java.util.Scanner读取CSV文件。 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(","); 我面临的挑战是lineScanner.useDelimiter(","); . My CSV has commas inside the text and escaped double Quotes: 我的CSV文本中有逗号,并且转义了双引号:

 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. 正如nhahtdh所提到的,您实际上应该使用解析器,因为CSV的工作方式比示例要复杂一些。

There are many libraries for this out there. 那里有很多图书馆。 One I've used and forked is csvfile . 我使用过并派生的一个是csvfile It's pretty easy to use and does the job right. 它非常易于使用并且可以正确完成工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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