string - 数字串在Groovy字母和数字排序

标签 string sorting groovy numeric

简单的问题,不知道有没有简单的答案。
有没有办法对包含字母和数字的字符串列表进行排序,但也要考虑数字?

例如,我的列表包含:

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

(字符串不一定有“组”这个词,它可以有其他词)

如果我对它进行排序,它会显示:
(2)
Group 1
Group 10
Group 2
Group 20
Group 3
Group 30

有没有办法像 (1) 那样排序?

谢谢

最佳答案

尝试这个:

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
}

这需要它在字符串中找到的最后一个数字,所以你可以写你想要什么,但“索引”应该是最后一个数字

关于string - 数字串在Groovy字母和数字排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12262901/

相关文章:

sorting - 如何找到矩阵排序的下界?

groovy - 如何在 Groovy 中 'Slice' 集合

c - 我想过滤数字流以获取某个范围内的值

python - 反转 Python 字符串中的单词(包括标点符号)

php - MYSQL:选择按字母顺序排序的父项与按字母顺序排序的子项分组

Groovy 提示意外的 token : ->

android - 为移动应用学习 geb 和 Spock

java - 带有加号字符的字符串匹配方法返回 false

c# - 从扫描仪(类似键盘)设备获取输入字符串 C# .net

c - 数组的种类及其位置