String Tokenizer : split string by comma and ignore comma in double quotes

后端 未结 6 2045
闹比i
闹比i 2021-01-18 03:58

I have a string like below -

value1, value2, value3, value4, \"value5, 1234\", value6, value7, \"value8\", value9, \"value10, 123.23\"

6条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-18 04:29

    Use a CSV parser like OpenCSV to take care of things like commas in quoted elements, values that span multiple lines etc. automatically. You can use the library to serialize your text back as CSV as well.

    String str = "value1, value2, value3, value4, \"value5, 1234\", " +
            "value6, value7, \"value8\", value9, \"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
    }
    

提交回复
热议问题