Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

splitting string into array with delimiter occurring multiple times in a row [duplicate]

Tags:

java

regex

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?

like image 216
codeNinja Avatar asked Dec 21 '25 10:12

codeNinja


2 Answers

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);
like image 77
Elliott Frisch Avatar answered Dec 24 '25 00:12

Elliott Frisch


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, ,,,, ,,,, ,,,, ,,,, ,,,, ,,,, ,,,, ,,,, ,,,, ,,,]
like image 35
YCF_L Avatar answered Dec 23 '25 22:12

YCF_L



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!