Java – string tokenizer: separate strings with commas and ignore commas with double quotes

I have a string like the following –

If I mark the string above, I get comma separated marks But I want to use the string marker after double quotation marks to ignore commas when splitting What should I say?

Thank you in advance

Shashi

Solution

Use a CSV parser like opencsv to handle commas in reference elements, automatically span multiple lines, etc You can also use this library to serialize text to CSV format

String str = "value1,\"value5,1234\"," +
        "value6,\"value8\",\"value10,123.23\"";

CSVReader reader = new CSVReader(new StringReader(str));

String [] tokens;
while ((tokens = reader.readNext()) != null) {
    System.out.println(tokens[0]); // value1
    System.out.println(tokens[4]); // value5,1234
    System.out.println(tokens[9]); // value10,123.23
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>