Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split string on comma and ignore comma in double quotes [duplicate]

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

and I would like the string to be spit like:

["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.

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

like image 966
callMeJava Avatar asked Nov 22 '25 06:11

callMeJava


1 Answers

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

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

Java code example:

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

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

}
like image 54
Bohus Andrei Avatar answered Nov 23 '25 21:11

Bohus Andrei