Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - string.split with colliding regexes

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.

like image 906
mettleap Avatar asked Aug 26 '26 08:08

mettleap


2 Answers

Always order the alternatives from the largest to the smalest:

String regex = "\"\",\"\"|,\"\"|\"\",|,";
like image 56
Toto Avatar answered Aug 28 '26 23:08

Toto


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

like image 30
jrook Avatar answered Aug 28 '26 22:08

jrook



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!