package cgeo.geocaching.sorting;

import cgeo.geocaching.cgCache;

import org.apache.commons.lang3.StringUtils;

import java.util.Scanner;

/**
 * sorts caches by name
 *
 */
public class NameComparator extends AbstractCacheComparator {

    @Override
    protected boolean canCompare(cgCache cache1, cgCache cache2) {
        return StringUtils.isNotBlank(cache1.name) && StringUtils.isNotBlank(cache2.name);
    }

    @Override
    protected int compareCaches(cgCache cache1, cgCache cache2) {
        // if the caches have a common prefix followed by a number, sort by the numerical value
        // so 2 is before 11, although "11" comes before "2"
        final String prefix = StringUtils.getCommonPrefix(cache1.name, cache2.name);
        if (StringUtils.length(prefix) > 0) {
            final String remaining1 = cache1.name.substring(prefix.length()).trim();
            if (remaining1.length() > 0 && Character.isDigit(remaining1.charAt(0))) {
                final String remaining2 = cache2.name.substring(prefix.length()).trim();
                if (remaining2.length() > 0 && Character.isDigit(remaining2.charAt(0))) {
                    final Integer number1 = (new Scanner(remaining1)).nextInt();
                    final Integer number2 = (new Scanner(remaining2)).nextInt();
                    return number1.compareTo(number2);
                }
            }
        }
        return cache1.name.compareToIgnoreCase(cache2.name);
    }
}

@@ -123,23 +123,61 @@
 va.util.
-Scann
+regex.Matcher;%0Aimport java.util.regex.Patt
 er
+n
 ;%0A%0A/**%0A 
@@ -269,16 +269,92 @@
 ator %7B%0A%0A
+    private static final Pattern NUMBER_PATTERN = Pattern.compile(%22%5C%5Cd+%22);%0A%0A
     @Ove
@@ -1286,26 +1286,23 @@
 mber1 = 
-(new Scann
+getNumb
 er(remai
@@ -1307,27 +1307,16 @@
 aining1)
-).nextInt()
 ;%0A      
@@ -1357,18 +1357,15 @@
 2 = 
-(new Scann
+getNumb
 er(r
@@ -1378,19 +1378,8 @@
 ng2)
-).nextInt()
 ;%0A  
@@ -1539,11 +1539,247 @@
 );%0A    %7D
+%0A%0A    private static Integer getNumber(final String string) %7B%0A        Matcher matcher = NUMBER_PATTERN.matcher(string);%0A        if (matcher.find()) %7B%0A            return Integer.valueOf(matcher.group());%0A        %7D%0A        return 0;%0A    %7D
 %0A%7D%0A

fix #671, performance of name sorting