gpt4 book ai didi

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

转载 作者:bug小助手 更新时间:2023-10-28 10:41:02 24 4
gpt4 key购买 nike

我有一个模糊的字符串:

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

我想用逗号分隔——但我需要忽略引号中的逗号。我怎样才能做到这一点?似乎正则表达式方法失败了;我想我可以在看到报价时手动扫描并输入不同的模式,但是使用预先存在的库会很好。 (edit:我想我的意思是已经是 JDK 的一部分或者已经是 Apache Commons 等常用库的一部分的库。)

上面的字符串应该分成:

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

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

最佳答案

试试:

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 在评论中提到的那样:

I prefer using Guava's Splitter, as it has saner defaults (see discussion above about empty matches being trimmed by String#split(), so I did:

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

关于Java:拆分逗号分隔的字符串但忽略引号中的逗号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1757065/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com