6

simple question, don't know if it gets a simple answer. Is there a way to sort a list of string wich contains letters and numbers, but considering the numbers as well?

For example, my list contains:

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

(The strings doesn't have the word "group" necessarily, it could have others words)

if I sort it, it shows:

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

Is there a way to sort it like (1) ?

Thanks

4

3 に答える 3

7

try this:

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 you want to compare first the number you have to change the internal if with:

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

This take te last number it found in the string, so you can write what do you want, but the 'index' should be the last number

于 2012-09-04T12:00:14.463 に答える
0

You can split the string in two sub-strings and then sort them separately.

于 2012-09-04T12:02:04.777 に答える
0

This should do the trick:

def myList= ["Group 1", "Group2", "Group3", "2", "Group20", "Group30", "1", "Grape 1"]
print (myList.sort { a, b -> a.compareToIgnoreCase b })
于 2013-08-07T12:16:29.750 に答える