尝试:
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(",(?=(?:[^"]*"[^"]*")*[^"]*$)"))
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)