CSVParser 不处理不带引号的字符串中的转义分隔符

CSVParser not handling escaped delimiters in unquoted strings

我在 Java 程序中使用 com.opencsv.CSVParser (5.1)。

                    final CSVParser csvParser =
                        new CSVParserBuilder()
                        .withSeparator(',')
                        .withQuoteChar('"')
                        .withEscapeChar('\')
                        .withIgnoreQuotations(true)
                        .build();

我的输入文件有

3,2.48,E #3,String with \, comma in it,0

我原以为第 4 个字段会以 "String with , comma in it" 结尾。但相反,解析器在转义逗号处将字符串拆分为两个字段,其中包含 "String with " 和 " 逗号"。 withEscapeChar() 的文档说:

Sets the character to use for escaping a separator or quote.

并且由于不需要转义引号分隔符,我假设(希望)这将允许我转义非引号字符串中的分隔符。无论是否使用 withIgnoreQuotations,我都试过了。

我是漏掉了什么,还是做错了什么?

我没有发现您的代码有任何问题 - 但我也无法按预期解析您的数据 - 我遇到了与您相同的问题。这感觉像是一个错误(令人惊讶)。如果这不是错误,那么正确的用法对我来说太晦涩了。

或者,您可以使用 Commons CSV:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-csv</artifactId>
    <version>1.8</version>
</dependency>

示例代码:

import com.opencsv.CSVReader;
import com.opencsv.CSVWriter;

...

private void commonsCsvTest() throws URISyntaxException, IOException {
    Path path = Paths.get(ClassLoader.getSystemResource("csv/escapes.csv").toURI());
    Reader in = new FileReader(path.toString());
    Iterable<CSVRecord> records = CSVFormat.DEFAULT.withEscape('\').parse(in);
    for (CSVRecord record : records) {
        System.out.println(record.get(3));
    }
}

使用输入文件 "escapes.csv" 中的数据,我们得到以下输出:

String with , comma in it

您显然可以更改读取输入文件的方式,以适应您的具体情况。