有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java中包含逗号时如何按逗号分割行

我想拆分必须符合csv语法但包含逗号的文本

例如: 帐户id标题文本

String line = "account123,2222,Thnaks for reaching out,\"Hey [[customerFirstName]], Thanks for reaching out to us.\""

String[] splitted = line.split(",");

结果:

splitted = {String[5]@539} 
 0 = "account123"
 1 = "2222"
 2 = "Thnaks for reaching out"
 3 = ""Hey [[customerFirstName]]"
 4 = " Thanks for reaching out to us.""

但我想

splitted = {String[4]@539} 
             0 = "account123"
             1 = "2222"
             2 = "Thnaks for reaching out"
             3 = "Hey [[customerFirstName]], Thanks for reaching out to us.\"

共 (2) 个答案

  1. # 1 楼答案

    以下是一个简单的解决方案:

    public static void main(String... args) {
        String line = "account123,2222,Thnaks for reaching out,\"Hey [[customerFirstName]], Thanks for reaching out to us.\",\"Hey [[customerFirstName]], Thanks for reaching out to us.\"";
        for (String s : splitByComma(line)) {
            System.out.println(s);
        }
    }
    
    private static List<String> splitByComma(String line) {
        String[] words = line.split(",");
        List<String> list = new ArrayList<>();
        for (int i = 0; i < words.length; ++i) {
            if (words[i].startsWith("\"")) { // collect from the start of the cell;
                String s = words[i].substring(1);
                while (i < words.length - 1) {
                    s += "," + words[++i].substring(0, words[i].length() - 1);
                    if (words[i++].endsWith("\"")) break; // jump out of the cell after the closing double quotes;
                }
                list.add(s);
                i ;
            } else {
                list.add(words[i]);
            }
        }
        return list;
    }
    

    您的输出将是:

    account123
    2222
    Thnaks for reaching out
    Hey [[customerFirstName]], Thanks for reaching out to us.
    Hey [[customerFirstName]], Thanks for reaching out to us.
    
  2. # 2 楼答案

    正如您所发现的,您的解决方案非常脆弱。好消息是,有许多更健壮的CSV解决方案可用。为了回答这个问题,我将使用openCSV,其中您的阅读代码变成:

    CSVReader csvReader = new CSVReader(reader);
    List<String[]> list = csvReader.readAll();
    reader.close();
    csvReader.close();
    

    希望这有助于