[英]Split, doesn't work first character
I have a problem with the method split
. 我对方法
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. 在第一种情况下,我得到
r1[0]="19/2009"
和r1[1]="34.40"
,这是正确的结果。 But in the second case I get r2[0]=""
, r2[1]="19/2009"
and r2[2]="34.40"
. 但在第二种情况下,我得到
r2[0]=""
, r2[1]="19/2009"
和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. 既然你给了
,
作为一个正则表达式, ,
分为二的字符串,所以你的字符串,19/2009
被分成两个部分。 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
. 第一部分是前
,
,这是没有任何如此""
,和第二部分,其为19/2009
,是在r2[1]
第三,由彼此分离的,
是在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. 它有点长,但它给你一个
List
作为输出,它比一个数组好得多。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.