简体   繁体   English

在openCSV中使用转义字符

[英]Using Escape characters in openCSV

I am using the default constructor and the default escape character which is backslash. 我正在使用默认的构造函数和默认的转义字符反斜杠。 So the CSV format is like this "value1","value2","value3","value4" 因此CSV格式类似于"value1","value2","value3","value4"

The values are read from the CSV file , Windows XP OS. 从CSV文件Windows XP OS中读取值。

Now the problem is that when the value as a double quote in it like this "aa"," I am "fine", what about u?", "232", I do not understand how to escape the double quote. 现在的问题是,当值中的双引号像这样的"aa"," I am "fine", what about u?", "232",我不知道如何转义双引号。

Can some one please help me here? 有人可以帮我吗?

Double quote the quote characters 用双引号引起来

    CSVParser csv = new CSVParser()

    String[] result = csv.parseLine('"aa","I am ""fine"", what about u?", "232"')

    assert result[0] == 'aa'
    assert result[1] == 'I am "fine", what about u?'
    assert result[2] == '232'

Update 更新

This answer was an extract from the following groovy test file OpenCSVTest.groovy : 这个答案是从以下常规测试文件OpenCSVTest.groovy中提取的

import groovy.util.GroovyTestCase
import au.com.bytecode.opencsv.CSVReader
import au.com.bytecode.opencsv.CSVParser

@Grapes([
    @Grab(group='net.sf.opencsv', module='opencsv', version='2.3')
])

class OpenCSVTest extends GroovyTestCase {

    void testParseQuote() {
        CSVParser csv = new CSVParser()

        String[] result = csv.parseLine('"aa","I am ""fine"", what about u?", "232"')

        assert result[0] == 'aa'
        assert result[1] == 'I am "fine", what about u?'
        assert result[2] == '232'
    }
}

Run as follows: 运行如下:

$ groovy OpenCSVTest
.
Time: 0.009

OK (1 test)

In your question you tell that you are using the default escape character which is backslash. 在您的问题中,您告诉您正在使用默认的转义字符,即反斜杠。 So you have to use the backslash... Like: "aa"," I am \\"fine\\", what about u?", "232" 因此,您必须使用反斜杠...像: "aa"," I am \\"fine\\", what about u?", "232"

Test it from code like this: 从这样的代码进行测试:

CSVParser csvParser = new CSVParser();
String[] parseLine = csvParser.parseLine("\"aa\",\" I am \"\"fine\"\", what about u?\", \"232\"");

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

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