String.split() — How do I treat consecutive delimi

2020-03-01 17:22发布

For two sample strings in variable temp such as these:

(1) "|RYVG|111|9|"
(2) "|RYVG|111||9|"

I want to do the following:

String splitRating[] = temp.split("\\|",);

But I want the result to be the same, which is:

splitrating[0] = ""
splitrating[1] = "RYVG"
splitrating[2] = "111"
splitrating[3] = "9

This means that I need to treat that double "|" as one delimiter. Is there any way to do this while still using String.split()?

4条回答
干净又极端
2楼-- · 2020-03-01 17:29

Try this:-

String splitRating[] = temp.split("\\|+");
查看更多
爷、活的狠高调
3楼-- · 2020-03-01 17:51

Yes it is possible

 class  Split
{
public static void main(String[] args) 
{
    String temp="|RYVG|111||9|";

    String splitRating[] = temp.split("\\|+");

    for(String split:splitRating){
    System.out.println(split);
}
}
    }
查看更多
Viruses.
4楼-- · 2020-03-01 17:52

StringUtils split method considers the consecutive delimiters as one delimiter.

org.apache.commons.lang.StringUtils.split("|"); 
查看更多
霸刀☆藐视天下
5楼-- · 2020-03-01 17:53

Add a + to match one or more instances of the pipe:

temp.split("\\|+");
查看更多
登录 后发表回答