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]