Java - string.split with colliding regexes

Viewed 55

I recently came across this problem and don't know how to solve it. I know that in the String class, we have the split method which accepts a regex and based on the regex, the given string is split into different strings and returned in a string array.

For example, if I have,

String s = "A,B,C";

and I do,

System.out.println(Arrays.toString(s.split(",")));

it will print [A, B, C] to output console.

Now let's say my string is

String s = "A,\"\"B\"\",\"\"C\"\",D";   //easier to read version: A,""B"",""C"",D

and I use the following regex to split the string,

String regex = ",|,\"\"|\"\",|\"\",\"\"";  // matches , OR ,"" OR "", OR "",""
System.out.println(Arrays.toString(s.split(regex)));

I get the output as [A, ""B, ""C, D]. How is the splitting working over here? And how do I define my regex so that I get [A, B, C, D] as my output?

NOTE: I know what I want to achieve can be done in other ways (like replaceAll method), but I only want to use the String.split for this problem, since I want to know how to use it in this case.

2 Answers

Always order the alternatives from the largest to the smalest:

String regex = "\"\",\"\"|,\"\"|\"\",|,";

As explained here, regex engine is eager it stops after it matches the comma (the first alternation) successfully. The other answer is one way to solve this problem. Another way is to use quantifiers:

,(\"\")?|\"\"(,\"\")?

See how it works at Regex101

Related