简体   繁体   中英

Split, doesn't work first character

I have a problem with the method split . I have this regex:

String regex = "[\s|\,]+";

And I have these two strings:

String s1 = "19/2009 , 34.40";

String s2 = ",19/2009 , 34.40";   // this is the same string wiht "," in the start

I apply the regex to the two strings:

String r1[] = s1.split(regex);  
String r2[] = s2.split(regex);

In the first case I get r1[0]="19/2009" and r1[1]="34.40" , this is the correct result. But in the second case I get r2[0]="" , r2[1]="19/2009" and r2[2]="34.40" . This is wrong, it should be the same result for the second string as for the first, without the empty string. What do I need to change for that?

Since you gave , as a regex, , splits your string in two, so your string ,19/2009 is split into two parts. The first part is before , , which is nothing so "" , and the second part, which is 19/2009 , is in r2[1] and the third, separated by another , , is in r2[2]=34.40 . Everything is working right.

使用Apache Commons的StringUtils ......

String r2[] = StringUtils.strip(s2, ", ").split(regex);

I would leave the regex as it is and do this

List<String> list = new ArrayList<String>(Arrays.asList(splitArray));
for (Iterator<String> iterator = list.iterator(); iterator.hasNext();) {
    if (iterator.next().isEmpty()) { // remove empty indexes
        iterator.remove();
    }
}

It's a little bit longer but it gives you a List as an output which is much better that an array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM