Reputation: 27
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?
Upvotes: 1
Views: 449
Reputation: 15844
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.
Upvotes: 0
Reputation: 4021
using Apache Commons' StringUtils...
String r2[] = StringUtils.strip(s2, ", ").split(regex);
Upvotes: 1
Reputation: 112
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.
Upvotes: 2