Ralf Wickum
Ralf Wickum

Reputation: 3270

Erase quotation mark at the end and the beginning

After read a cvs file, I have a lot of

"

quotation marks. At least all the fields begin with double quotation marks and end with two as well. It might also happen, that in between there are also further quotation marks, as in following example:

""Entry in "cvs" file""

Currently I remove them by:

String raw_string = myString.replace("\"", "");

or

String raw_string = myString.substring(1, mystring.length() -1);

since it is the first and last charachter..

What is more efficient? Are there other more efficient methods?

Upvotes: 1

Views: 64

Answers (3)

Jaumzera
Jaumzera

Reputation: 2359

You can do that with a Regex:

String rawString = myString.replaceAll("['\"](.+)['\"]", "$1");

"a text"
"another text"
"a text with "nested" quotation"

will return:

a text
a greater text
a text with "nested" quotation

Or you can simply remove all quotation marks from the string:

String rawString = myString.replaceAll("['\"]+", "");

Upvotes: 1

W.K.S
W.K.S

Reputation: 10095

You can use a regex to find all the quotation marks at the beginning and at the end of the string and replace them with "".

myString.replaceAll("^\"*|\"*$","");

Try it on ideone.

Upvotes: 1

Jan-Espen Oversand
Jan-Espen Oversand

Reputation: 41

Have you considered using something like opencsv to read the csv-files?

http://opencsv.sourceforge.net/

(also available in maven central)

Using a library to read the csv-files may be of convenience, but it will probably handle encoded double quotes in the strings as well.

Upvotes: 0

Related Questions