我有一个这样的字符串:
foo,bar,c;qual="baz,blurb",d;junk="quux,syzygy"
我想用逗号分隔,但我需要忽略引号中的逗号。我该怎么做呢?regexp方法似乎失败了;我想我可以手动扫描,并在看到报价时进入不同的模式,但如果使用已有的库就更好了。(编辑:我想我指的是已经是JDK的一部分或者已经是Apache Commons等常用库的一部分的库。)
上面的字符串应该分成:
foo
bar
c;qual="baz,blurb"
d;junk="quux,syzygy"
注意:这不是一个CSV文件,它是一个包含在一个更大的整体结构文件中的单个字符串
Try:
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"
换句话说:仅当逗号前面有0个引号或偶数个引号时,才在逗号上进行分隔。
或者,对眼睛更友好一点:
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);
}
}
}
结果和第一个例子一样。
EDIT
正如@MikeFHay在评论中提到的:
我更喜欢使用Guava的Splitter,因为它有更理智的默认值(见上面关于空匹配被String#split()修剪的讨论,所以我这样做了:
Splitter.on (Pattern.compile (",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)"))