3

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?

codeNinja
  • 1,442
  • 3
  • 25
  • 61
  • You should just split on ',' and then filter the array for strings of length 0. – Conor Nov 11 '17 at 19:47
  • this is not duplicate of that question @Pshemo if you use `.split(",{3}", -1);` you will get 17 and not 16 like the OP ask i suggest to reopen it again please – Youcef LAIDANI Nov 11 '17 at 20:42
  • 2
    @YCF_L I assumed that this was just OPs miscalculation. Will reopen if OP will clarify his reasons for 16 vs 17 values. – Pshemo Nov 11 '17 at 20:46
  • yes it was a miscalculation on my part. I needed `17` – codeNinja Nov 12 '17 at 15:03

2 Answers2

2

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);
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
1

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, ,,,, ,,,, ,,,, ,,,, ,,,, ,,,, ,,,, ,,,, ,,,, ,,,]
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140