String.split() — How do I treat consecutive delimiters as one?

你离开我真会死。 提交于 2019-11-30 04:06:19

问题


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()?


回答1:


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

temp.split("\\|+");



回答2:


Try this:-

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



回答3:


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);
}
}
    }



回答4:


StringUtils split method considers the consecutive delimiters as one delimiter.

org.apache.commons.lang.StringUtils.split("|"); 


来源:https://stackoverflow.com/questions/18288760/string-split-how-do-i-treat-consecutive-delimiters-as-one

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!