2012-09-04 179 views
4

簡單的問題,不知道它是否得到一個簡單的答案。 有沒有辦法對一個包含字母和數字的字符串列表進行排序,但是考慮到這些數字呢?Groovy中用字母和數字排序的數字字符串

例如,我的列表中包含:

(1) ["Group 1", "Group2", "Group3", "Group10", "Group20", "Group30"] 

(琴絃沒有詞「集團」不一定,也可能有其他人的話)

如果我排序它,它顯示:

(2) 
Group 1 
Group 10 
Group 2 
Group 20 
Group 3 
Group 30 

有沒有一種方法來排序它像(1)?

感謝

回答

6

試試這個:

def test=["Group 1", "Group2", "Group3", "2", "Group20", "Group30", "1", "Grape 1", "Grape 12", "Grape 2", "Grape 22"] 

test.sort{ a,b -> 
    def n1 = (a =~ /\d+/)[-1] as Integer 
    def n2 = (b =~ /\d+/)[-1] as Integer 

    def s1 = a.replaceAll(/\d+$/, '').trim() 
    def s2 = b.replaceAll(/\d+$/, '').trim() 

    if (s1 == s2){ 
     return n1 <=> n2 
    } 
    else{ 
     return s1 <=> s2 
    } 
} 

println test 

如果你想先來比較,你必須改變內部數量如果有:

if (n1 == n2){ 
    return s1 <=> s2 
} 
else{ 
    return n1 <=> n2 
} 

這需要TE最後一個號碼它發現在字符串中,所以你可以寫你想要的,但'索引'應該是最後一個數字

+0

很不錯的嘗試兄弟,但測試這一點:'高清測試= 「1組」, 「組2」, 「組3」, 「2」,「Group20 「,」Group30「,」1「,」葡萄1「,」葡萄12「,」葡萄2「,」葡萄22「] –

+0

應該是什麼結果?它應該首先檢查數字比字符串?或首先比字符串的字符? – rascio

+0

顯示來自測試'[組1,1,葡萄1,組2,葡萄2,組3,葡萄12,組20,葡萄22,組30]的println'你在這裏看到什麼順序? –

0

您可以將字符串拆分爲兩個子字符串,然後分別對它們進行排序。

0

這應該做的伎倆:

def myList= ["Group 1", "Group2", "Group3", "2", "Group20", "Group30", "1", "Grape 1"] 
print (myList.sort { a, b -> a.compareToIgnoreCase b })