用引号引起来的逗号分隔字符串

问题描述 投票:1回答:2

我看到有几个类似的问题,但是我没有找到满意的答案。我有一个逗号分隔的文件,其中每一行看起来都像这样:

4477,52544,,,P,S,    ,,SUSAN JONES,9534 Black Bear Dr,,"CITY, NV 89506",9534 BLACK BEAR DR,,CITY,NV,89506,2008,,,,  ,     ,    , ,,1

出现的问题是令牌通过引号“ CITY,NV 89506”转义为逗号时>

我需要一个结果,在该结果中处理了转义的令牌并包括了每个令牌,甚至是空的令牌。

java regex split tokenize
2个回答
2
投票

考虑适当的CSV解析器,例如opencsv。它会经过高度测试(不同于新的本地解决方案),并且能够处理您描述的边缘条件(以及您尚未考虑的很多条件)。

在下载中,有一个示例文件夹,其中包含带有以下行的“ addresses.csv”:

Jim Sample,"3 Sample Street, Sampleville, Australia. 2615",[email protected]

在同一目录中,文件AddressExample.java解析该文件,并且与您的问题高度相关。


0
投票

这是使用提供的java.lang.String方法回答您的问题的一种方法。我相信它可以满足您的需求。

private final char QUOTE = '"';
private final char COMMA = ',';
private final char SUB = 0x001A; // or whatever character you know will NEVER
    // appear in the input String

public void readLine(String line) {
    System.out.println("original: " + line);

    // Replace commas inside quoted text with substitute character
    boolean quote = false;
        for (int index = 0; index < line.length(); index++) {
        char ch = line.charAt(index);
        if (ch == QUOTE) {
            quote = !quote;
        } else if (ch == COMMA && quote) {
            line = replaceChar(line, index, SUB);
            System.out.println("replaced: " + line);
        }
    }

    // Strip out all quotation marks
    for (int index = 0; index < line.length(); index++) {
        if (line.charAt(index) == QUOTE) {
            line = removeChar(line, index);
            System.out.println("stripped: " + line);
        }
    }

    // Parse input into tokens
    String[] tokens = line.split(",");
    // restore commas in place of SUB characters
    for (int i = 0; i < tokens.length; i++) {
        tokens[i] = tokens[i].replace(SUB, COMMA);
    }

    // Display final results
    System.out.println("Final Parsed Tokens: ");
    for (String token : tokens) {
        System.out.println("[" + token + "]");
    }
}

private String replaceChar(String input, int position, char replacement) {
    String begin = input.substring(0, position);
    String end = input.substring(position + 1, input.length());
    return begin + replacement + end;
}

private String removeChar(String input, int position) {
    String begin = input.substring(0, position);
    String end = input.substring(position + 1, input.length());
    return begin + end;
}
© www.soinside.com 2019 - 2024. All rights reserved.