[英]Split, doesn't work first character
我對方法split
有問題。 我有這個正則表達式:
String regex = "[\s|\,]+";
我有這兩個字符串:
String s1 = "19/2009 , 34.40";
String s2 = ",19/2009 , 34.40"; // this is the same string wiht "," in the start
我將正則表達式應用於兩個字符串:
String r1[] = s1.split(regex);
String r2[] = s2.split(regex);
在第一種情況下,我得到r1[0]="19/2009"
和r1[1]="34.40"
,這是正確的結果。 但在第二種情況下,我得到r2[0]=""
, r2[1]="19/2009"
和r2[2]="34.40"
。 這是錯誤的,它應該與第一個字符串的結果相同,而不是空字符串。 我需要改變什么呢?
既然你給了,
作為一個正則表達式, ,
分為二的字符串,所以你的字符串,19/2009
被分成兩個部分。 第一部分是前,
,這是沒有任何如此""
,和第二部分,其為19/2009
,是在r2[1]
第三,由彼此分離的,
是在r2[2]=34.40
。 一切正常。
使用Apache Commons的StringUtils ......
String r2[] = StringUtils.strip(s2, ", ").split(regex);
我會保留正則表達式並執行此操作
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();
}
}
它有點長,但它給你一個List
作為輸出,它比一個數組好得多。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.