简单的问题,不知道有没有简单的答案。
有没有办法对包含字母和数字的字符串列表进行排序,但也要考虑数字?
例如,我的列表包含:
(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/