I have the following string:
Beans,,,Beans,,,Beans,,,Beans,,,playstation,,,Cool Beans,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
I am using this:
//split the string
String[] rowValues = row.split(",,,");
I expect that rowValues have length of 17.
But in the above case the length is only 6. How do i deal with the ,,, occurring multiple times in a row?
First, you can use {3} to indicate you want three of the character in your regular expression. Second, pass a negative limit to String.split(String, int) which the linked Javadoc notes If n is non-positive then the pattern will be applied as many times as possible and the array can have any length. Like,
String[] rowValues = row.split(",{3}", -1);
which will return 17 values with your provided input; if you literally need 16 then you can specify that instead
String[] rowValues = row.split(",{3}", 16);
One way is to put after each three ,,, a separator for example ,,,_ then split with this separator instead :
String row = "Beans,,,Beans,,,Beans,,,Beans,,,playstation,,,Cool "
+ "Beans,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,";
String[] list = Arrays.stream(row.replaceAll("(,,,)", "$1_").split("_"))
.map(t -> t.replaceAll("(.+),{3}$", "$1"))
.toArray(String[]::new);
System.out.println(list.length);//size = 16
Outputs
[Beans, Beans, Beans, Beans, playstation, Cool Beans, ,,,, ,,,, ,,,, ,,,, ,,,, ,,,, ,,,, ,,,, ,,,, ,,,]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With