CSV データをパースする

ExcelCSV データは以下のルール(エスケープ)がある。

  • ダブルクォートで囲った場合
    • カンマは文字として扱う。
    • ダブルクォートが2つ連続すると、1文字として扱う。

CSV の各項目を取り出したいとき、正規表現を使うと簡単。
参考: http://oraclesqlpuzzle.hp.infoseek.co.jp/regex/regex-4-18.html

以下がサンプル。ただし、不正なフォーマットだと動作しない。

public class Test {

    public static void main(String[] args) {
        String line = args[0];
        String[] arr = line.split(",(?=(([^\"]*\"){2})*[^\"]*$)");
        for (String v : arr) {
            System.out.println(trimQuotes(v));
        }
    }

    static String trimQuotes(String s) {
        if (s == null) return s;
        int length = s.length();
        if (length < 2) return s;

        char first = s.charAt(0);
        char last = s.charAt(length - 1);
        if (first == '"' && last == '"') {
            s = s.substring(1, length - 1);
        }

        return s.replace("\"\"", "\"");
    }
}