How to split a comma separated String while ignoring escaped commas?
Try:
String array[] = str.split("(?<!\\\\),");
Basically this is saying split on a comma, except where that comma is preceded by two backslashes. This is called a negative lookbehind zero-width assertion.
The regular expression
[^\\],
means "match a character which is not a backslash followed by a comma" - this is why patterns such as t,
are matching, because t
is a character which is not a backslash.
I think you need to use some sort of negative lookbehind, to capture a ,
which is not preceded by a \
without capturing the preceding character, something like
(?<!\\),
(BTW, note that I have purposefully not doubly-escaped the backslashes to make this more readable)