Abdullah
Abdullah

Reputation: 41

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"

The values are read from the CSV file , 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.

Can some one please help me here?

Upvotes: 3

Views: 9422

Answers (2)

Mark O'Connor
Mark O'Connor

Reputation: 77961

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:

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)

Upvotes: 1

Kai
Kai

Reputation: 39641

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"

Test it from code like this:

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

Upvotes: 0

Related Questions