Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting a string by value between quotation marks in Java

Tags:

java

string

split

I'm reading in a file in Java and want to split each line by the value inside quotation marks. For example, a line would be...

"100","this, is","a","test"

I would like the array to look like..

[0] = 100
[1] = this, is
[2] = a
[3] = test

I normally split by comma, but since some of the fields include a comma (position 1 in the example above) it's not really suitable.

Thanks.

like image 516
user3722194 Avatar asked Oct 23 '14 14:10

user3722194


1 Answers

You can split it the following way:

String input = "\"100\",\"this, is\",\"a\",\"test\"";
for (String s:input.split("\"(,\")*")) {
    System.out.println(s);
}

Output

100
this, is
a
test

Note The first array element will be empty.

like image 73
Mena Avatar answered Sep 29 '22 00:09

Mena