我正在尝试为 TreeMap 实现一个比较器,其中关键条目是以下形式的字符串
1a
2b
11a
11b
14
16
我可以使用这个正则表达式轻松识别需要额外处理的字符串
[0-9]+[a-zA-Z]+
使用简单的 [0-9]+ 正则表达式我可以轻松找到字符串上的初始数字,我的问题是如何将它们分开以便让我分别比较整数值和字符串字符?
编辑: 样本数据高于预期输出,理想情况下是一个字符串数组,位置 0 是整数值,位置 1 是字符串值,即
[1,a]
[2,b]
[11,a]
[11,b]
最佳答案
这是使用您建议的正则表达式的一种方法:
new Comparator<String>() {
Pattern p = Pattern.compile("([0-9]+)[a-zA-Z]+");
private String getNum(String s) {
Matcher m = p.matcher(s);
return m.matches() ? m.group(1) : s;
}
@Override
public int compare(String o1, String o2) {
o1 = getNum(o1);
o2 = getNum(o2);
return Integer.compare(Integer.parseInt(o1),
Integer.parseInt(o2));
}
};
<小时/>
如果您使用的是Java 8,则可以这样做
private static Pattern p = Pattern.compile("([0-9]+)[a-zA-Z]+");
private static int getNum(String s) {
Matcher m = p.matcher(s);
return Integer.parseInt(m.matches() ? m.group(1) : s);
}
然后使用
Comparator.comparing(YourClass::getNum))
<小时/>
另一种不使用您建议的正则表达式的方法是这样做
Comparator.comparing(s -> Integer.parseInt(s.replaceAll("[a-zA-Z]", ""))));
关于java - 拆分不带分隔符的字母数字字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28190541/