Regex to retrieve last digits from a string and sort them

saurabh kumar :

I have a list of string which I want to sort them using the last digits present in the string, I have tried this using below code, but for some reasons, it's picking digit present before the last digit as well, for instance in "abc\xyz 2 5" string it's picking 25 instead of just 5 because of which it is sorting it incorrectly. May I know what's incorrect in my regex?

Note: My last two digits will always be timestamp like 1571807700009 1571807700009.

Here's what I have tried so far.

public static void second() {   
List<String> strings = Arrays.asList("abc\\xyz 2 5", "abc\\\\xyz 1 8", "abc\\\\xyz 1 9", "abc\\\\xyz 1 7", "abc\\\\xyz 1 3");       
Collections.sort(strings, new Comparator<String>() {
        public int compare(String o1, String o2) {
            return (int) (extractInt(o1) - extractInt(o2));
        }

        Long extractInt(String s) {
            String num = s.replaceAll("\\D", "");
            return Long.parseLong(num);
        }
    });
    System.out.println(strings);

}

Output

[abc\\xyz 1 3, abc\\xyz 1 7, abc\\xyz 1 8, abc\\xyz 1 9, abc\xyz 2 5]

Expected Output

[abc\\xyz 1 3, abc\\xyz 2 5, abc\\xyz 1 7, abc\\xyz 1 8, abc\xyz 1 9]
WJS :

Using a stream, sort only on the last integer by replacing the previous portion of the string with an empty string. You can also take advantage of the API Comparator interface by passing that value to the comparing method.

   List<String> strings = Arrays.asList("abc\\xyz 2 5", "abc\\\\xyz 1 8",
      "abc\\\\xyz 1 9", "abc\\\\xyz 1 7", "abc\\\\xyz 1 3");

   strings = strings.stream()
       .sorted(Comparator.comparing(s -> Long.valueOf(s.replaceAll(".*\\s+", ""))))
       .collect(Collectors.toList());

   System.out.println(strings);

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=323548&siteId=1