在逗号上分割字符串,并忽略双引号中的逗号 [英] Split string on comma and ignore comma in double quotes

查看:317
本文介绍了在逗号上分割字符串,并忽略双引号中的逗号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用Java进行编码,并且有一个方法可以返回看起来像这样的字符串:

I am coding in Java and have a method that returns a string that looks something like this:

0, 2, 23131312,"This, is a message", 1212312

我希望字符串像这样:

["0", "2", "23131312", "This, is a message", "1212312"]

当我在逗号上使用拆分字符串方法时,它也会拆分这是一条消息",这也是我所不希望的.我希望它忽略该特殊的逗号,并尽可能删除双引号.

When I use the split string method on comma, it splits the "This, is a message" as as well, which I don't want. I would like it to ignore that particular comma and get rid of double quotes, if possible.

我查找了一些答案,而CSV似乎就是这样做的方法.但是,我不太了解.

I looked up some answers and CSV seems to be the way to do it. However, I don't understand it properly.

推荐答案

我认为您可以从此处使用正则表达式,(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$):

I think you can use the regex,(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$) from here: Splitting on comma outside quotes

您可以在此处测试模式: http://regexr.com/3cddl

You can test the pattern here: http://regexr.com/3cddl

Java代码示例:

public static void main(String[] args) {
    String txt = "0, 2, 23131312,\"This, is a message\", 1212312";

    System.out.println(Arrays.toString(txt.split(",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)")));

}

这篇关于在逗号上分割字符串,并忽略双引号中的逗号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆