在逗号上分割字符串,并忽略双引号中的逗号

问题描述:

我正在用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(",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)")));

}