Splitting string in Java only when delimiter is surrounded by quotes
Let's say I have the following line:
"John Doe","IT,SI","foo, bar"
And I would like to split it into:
["John Doe", "IT,SI", "foo, bar"]
I thought to implement something like this:
String line = "\"John Doe\",\"IT,SI\",\"foo, bar\"";
String[] lineItems = line.split("\",\"");
for (String lineItem : lineItems) {
lineItem.removeAll("\"");
}
It does a thing, however it doesn't seem to be a state of the art. Is there a better solution?
+3
source to share
4 answers
You want words between double quotes, so instead of splitting the string, you can use the following regex to extract them:
/"([^"]+)"/g
See demo https://regex101.com/r/hC3cW2/1
0
source to share