小编典典

Java:分割逗号分隔的字符串,但忽略引号中的逗号

java

我有一个模糊的字符串,像这样:

foo,bar,c;qual="baz,blurb",d;junk="quux,syzygy"

我想按逗号分割-但我需要忽略引号中的逗号。我怎样才能做到这一点?似乎正则表达式方法失败了;我想我可以在看到报价时手动扫描并进入其他模式,但是使用预先存在的库会很好。(编辑:我想我的意思是那些已经属于JDK或已经属于诸如Apache Commons之类的常用库的库。)

上面的字符串应分为:

foo
bar
c;qual="baz,blurb"
d;junk="quux,syzygy"

注意:这不是CSV文件,它是文件中包含的单个字符串,具有较大的整体结构


阅读 780

收藏
2020-02-25

共1个答案

小编典典

尝试:

public class Main { 
    public static void main(String[] args) {
        String line = "foo,bar,c;qual=\"baz,blurb\",d;junk=\"quux,syzygy\"";
        String[] tokens = line.split(",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)", -1);
        for(String t : tokens) {
            System.out.println("> "+t);
        }
    }
}

输出:

> foo
> bar
> c;qual="baz,blurb"
> d;junk="quux,syzygy"

换句话说:仅当逗号逗号为零或引号是偶数时,才对逗号进行拆分。

或者,对眼睛有点友好:

public class Main { 
    public static void main(String[] args) {
        String line = "foo,bar,c;qual=\"baz,blurb\",d;junk=\"quux,syzygy\"";

        String otherThanQuote = " [^\"] ";
        String quotedString = String.format(" \" %s* \" ", otherThanQuote);
        String regex = String.format("(?x) "+ // enable comments, ignore white spaces
                ",                         "+ // match a comma
                "(?=                       "+ // start positive look ahead
                "  (?:                     "+ //   start non-capturing group 1
                "    %s*                   "+ //     match 'otherThanQuote' zero or more times
                "    %s                    "+ //     match 'quotedString'
                "  )*                      "+ //   end group 1 and repeat it zero or more times
                "  %s*                     "+ //   match 'otherThanQuote'
                "  $                       "+ // match the end of the string
                ")                         ", // stop positive look ahead
                otherThanQuote, quotedString, otherThanQuote);

        String[] tokens = line.split(regex, -1);
        for(String t : tokens) {
            System.out.println("> "+t);
        }
    }
}

其结果与第一个示例相同。

编辑
正如@MikeFHay在评论中提到的:

我更喜欢使用Guava的Splitter,因为它的默认值更合理(请参见上面有关用修饰的空匹配的讨论String#split(),所以我这样做了:

Splitter.on(Pattern.compile(",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)"))
2020-02-25