Java 将字符串拆分为一行中多次出现分隔符的数组

Java 将字符串拆分为一行中多次出现分隔符的数组,java,regex,Java,Regex,我有以下字符串: Beans,,,Beans,,,Beans,,,Beans,,,playstation,,,Cool Beans,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, 我用的是: //split the string String[] rowValues = row.split(",,,"); 我希望rowValues的长度为17 但在上述情况下,长度仅为6。如何处理一行中多次出现的,,?首先,可以使用{3}表示希望正则表达式中包含三个字符。第二,传递链接的Ja

我有以下字符串:

Beans,,,Beans,,,Beans,,,Beans,,,playstation,,,Cool Beans,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
我用的是:

//split the string
String[] rowValues = row.split(",,,");
我希望
rowValues
的长度为
17


但在上述情况下,长度仅为6。如何处理一行中多次出现的
,,

首先,可以使用
{3}
表示希望正则表达式中包含三个字符。第二,传递链接的Javadoc注释的负限制,如果
n
为非正,则将尽可能多次应用该模式,并且该数组可以有任何长度。像

它将返回17个值和您提供的输入;如果你真的需要16,那么你可以指定它

String[] rowValues = row.split(",{3}", 16);

一种方法是在每三个
,,
后面放置一个分隔符,例如
,,\u
,然后使用此分隔符拆分:

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
输出

[Beans, Beans, Beans, Beans, playstation, Cool Beans, ,,,, ,,,, ,,,, ,,,, ,,,, ,,,, ,,,, ,,,, ,,,, ,,,]

您只需在“,”上拆分,然后过滤数组中长度为0的字符串。如果使用
.split(“,{3},-1”),则这与问题@Pshemo不重复你会得到17,而不是像OP那样的16,我建议你重新打开它please@YCF_L我以为这只是误算。如果OP能澄清16对17的理由,他将重新开张。是的,这是我的一个误算。我需要
17
[Beans, Beans, Beans, Beans, playstation, Cool Beans, ,,,, ,,,, ,,,, ,,,, ,,,, ,,,, ,,,, ,,,, ,,,, ,,,]