0

I am trying to split a string by comma, however I don't want to split if the comma is surrounded by quotes.

Here is what I am trying to do:

String s = "today,\"is, clear\",and sunny";
String[] split = s.split("(?>!\"[0-z]*),(?![0-z]*\")");

And the contents of split would be ["today", "\"is, clear\"", "and sunny"], but I'm having trouble getting the regex to work right.

Nathan
  • 15
  • 3

1 Answers1

1

One option would be to use a negative lookahead which asserts that a split on comma only happens when an even number of double quotes follows. Appreciate that commas inside double quotes would always have an odd number of double quotes following, assuming your quotes are always balanced.

String s = "today,\"is, clear\",and sunny";
String[] parts = s.split(",(?!.*\"(?:.*\".*\")*$)");
System.out.println(Arrays.toString(parts));

This prints:

[today, "is,  clear", and sunny]
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360