【问题标题】:Splitting alphanumeric strings without a deliminator拆分不带分隔符的字母数字字符串
【发布时间】:2015-01-28 11:00:26
【问题描述】:

我正在尝试为 TreeMap 实现一个比较器,其中键条目是表单的字符串

1a
2b
11a
11b
14 
16

我可以使用这个正则表达式轻松识别需要额外处理的字符串

[0-9]+[a-zA-Z]+

使用简单的 [0-9]+ 正则表达式,我可以轻松找到字符串上的初始数字,我的问题是如何将它们拆分,然后分别比较整数值和字符串字符?

编辑: 样本数据高于预期输出理想情况下将是一个字符串数组,位置 0 是整数值,位置 1 是字符串值,即

[1,a]
[2,b]
[11,a]
[11,b]

【问题讨论】:

  • 您能否添加一些示例数据(输入和预期输出)?
  • 我猜你可以捕捉数字和字母元素并在之后处理它们。

标签: java regex string


【解决方案1】:

这是使用您建议的正则表达式的一种方法:

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]", ""))));

【讨论】:

  • 谢谢这让我找到了解决方案,而不是使用 match 我使用 find 来确定字符串中的内容以及我可以从哪里得到它。非常感谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-13
  • 2016-09-04
  • 2014-06-29
相关资源
最近更新 更多