Groovy中带有字母和数字的数字字符串排序

6

简单的问题,不知道是否能得到简单的答案。有没有一种方法可以对包含字母和数字的字符串列表进行排序,但同时考虑到数字?

例如,我的列表包含:

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

字符串并不一定含有单词"组(group)",可能含有其他单词。

如果我对其进行排序,会显示如下:

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

有没有一种方法可以像(1)那样进行排序?
谢谢
3个回答

7

试试这个:

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替换为:

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

此函数会取出字符串中最后一个数字,所以您可以写想要的内容,但是“index”应该是最后一个数字。


应该得到什么结果?它应该先检查数字还是字符串?或者先检查字符串再检查数字? - rascio
展示来自测试的println [Group 1, 1, Grape 1, Group2, 2, Grape 2, Group3, Grape 12, Group20, Grape 22, Group30]。你在这里看到什么顺序? - AA.
真酷!+10。你可以用s1 <=> s2 : n1 <=> n2更简洁些。 - AA.
1
可能需要一个if来检查integer是否存在。但这太多余了。非常好的回答,兄弟。 - AA.
这真的很棒,非常感谢。 我曾经用一个“丑陋”的解决方法,但它只能按数字排序。 如果有人在意的话,这就是它:<br/>def grupos = ["Group 1", "Group2", "Group3", "2", "Group20", "Group30", "1", "Grape 1", "Grape 12", "Grape 2", "Grape 22"] println grupos.sort{it.replaceAll("[^\\d]", "")!= ""? it.replaceAll("[^\\d]", "").toLong() : it}; - Johnny C.
显示剩余4条评论

0

这应该能解决问题:

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

0
你可以将字符串分成两个子字符串,然后分别进行排序。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接