# 如何排序字母数字字符串 [英] How to sort Alphanumeric String

### 问题描述

1some，2some，20some，21some，3some，some

I have a problem with sorting strings which include integers. If I use the below code I get sorting like: 1some, 2some, 20some, 21some, 3some, some

1some，2some，3some，20some，21some，some

However I want it sorted like: 1some, 2some, 3some, 20some, 21some, some

``````Collections.sort(selectedNodes,
new Comparator<DefaultMutableTreeNode>() {
@Override
public int compare(DefaultMutableTreeNode o1,
DefaultMutableTreeNode o2) {
return o1.getUserObject().toString()
.compareTo(o2.getUserObject().toString());
}
});
``````

### 推荐答案

Here is a self-contained example on how to do this (not particularly optimized):

``````final Pattern p = Pattern.compile("^\\d+");
String[] examples = {
"1some", "2some", "20some", "21some", "3some", "some", "1abc", "abc"
};
Comparator<String> c = new Comparator<String>() {
@Override
public int compare(String object1, String object2) {
Matcher m = p.matcher(object1);
Integer number1 = null;
if (!m.find()) {
return object1.compareTo(object2);
}
else {
Integer number2 = null;
number1 = Integer.parseInt(m.group());
m = p.matcher(object2);
if (!m.find()) {
return object1.compareTo(object2);
}
else {
number2 = Integer.parseInt(m.group());
int comparison = number1.compareTo(number2);
if (comparison != 0) {
return comparison;
}
else {
return object1.compareTo(object2);
}
}
}
}
};
List<String> examplesList = new ArrayList<String>(Arrays.asList(examples));
Collections.sort(examplesList, c);
System.out.println(examplesList);
``````

``````[1abc, 1some, 2some, 3some, 20some, 21some, abc, some]
``````

• 该示例使用常量`模式`推断一个数字是否在` String `的起始位置。

• 如果第一个不存在` String `，它将其与第二个进行比较。

• 如果确实存在于第一个中，它会检查第二个。

• 如果第二个不存在，则按原样比较两个` String `，再次

• 如果在两者中，它比较` Integer `而不是整个` String ` s，因此导致数字比较而不是词典编纂

• 如果数字比较相同，则返回整个` String ` s的字典比较（谢谢 MihaiC 发现这一个）

• The example uses a constant `Pattern` to infer whether a number is in the `String`'s starting position.
• If not present in the first `String`, it compares it as is to the second.
• If present indeed in the first, it checks the second.
• If not present in the second, it compares the two `String`s as is, again
• If present in both, it compares the `Integer`s instead of the whole `String`s, hence resulting in a numerical comparison rather than a lexicographical one
• If the number compare identical, it goes back to lexicographic comparison of the whole `String`s (thanks MihaiC for spotting this one)