1 package net.mograsim.plugin.util;
3 import java.math.BigInteger;
4 import java.util.Comparator;
5 import java.util.regex.Matcher;
6 import java.util.regex.Pattern;
9 * Compares Strings respecting integers that appear in the strings with positions in common.<br>
10 * Note that 0003 , 03 and 3 are considered to be at the same level; however if there is no further difference, lexicographic ordering is
11 * applied to ensure the comparator meets the {@link Comparator contract} (this will sort "foo_02" before "foo_2").
13 * @author Christian Femers
16 public class NumberRespectingStringComparator implements Comparator<String>
18 public static final NumberRespectingStringComparator CASE_SENSITIVE = new NumberRespectingStringComparator();
20 private static final Pattern PATTERN = Pattern.compile("\\d+", Pattern.DOTALL);
22 private final Comparator<CharSequence> comp = CharSequence::compare;
24 private NumberRespectingStringComparator()
29 public int compare(String o1, String o2)
31 Matcher m1 = PATTERN.matcher(o1);
32 Matcher m2 = PATTERN.matcher(o2);
35 while (m1.find() && m2.find() && m1.start() - pos1 == m2.start() - pos2)
37 int charsCompRes = comp.compare(o1.subSequence(pos1, m1.start()), o2.subSequence(pos2, m2.start()));
38 if (charsCompRes != 0)
41 BigInteger num1 = new BigInteger(m1.group());
42 BigInteger num2 = new BigInteger(m2.group());
43 int compRes = num1.compareTo(num2);
50 int restCompRes = comp.compare(o1.substring(pos1), o2.substring(pos2));
53 return comp.compare(o1, o2);