java string split 引号_Java:分割逗号分隔的字符串,但忽略引号中的逗号

小编典典

尝试:

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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值