Sorting a numeric string with letters and numbers in Groovy

a simple question, I don’t know if he will get a simple answer. Is there a way to sort the list of strings containing letters and numbers, but also considering the numbers?

For example, my list contains:

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

(Lines do not necessarily contain the word "group", may have other words)

if I sort it, it shows:

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

Is there any way to sort it as (1)?

thanks

+4
source share
3 answers

try the following:

 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 first compare the number you must change if:

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

This will take the last number found in the string, so you can write whatever you want, but the β€œindex” should be the last number

+6
source

You can split the string into two substrings, and then sort them separately.

0
source

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 }) 
0
source

Source: https://habr.com/ru/post/1432259/


All Articles