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


Below regex works well for this case.



String[] lineItems = line.split("(?<=\"),(?=\")");

      

+1


source


The following should solve the problem



line.split("(?<=\"),(?=\")") 

      

+1


source


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


(\b[^"]+)

      

Or you can also call it:

(?P<names>\b[^"]+)
OR
(?<names>\b[^"]+)

      

Not sure if java supports P <> or <>

0


source







All Articles