如何使用正则表达式获取字符串中的最后一个数字?

时间:2017-03-13 05:08:44

标签: java

我的字符串是 - 20 of 568 matches。我想要568被选中并显示出来。

我可以使用什么正则表达式来完成此任务?

2 个答案:

答案 0 :(得分:1)

public static void main(String[] args) {
    System.out.println(getSpecSubString("20 matches out of 568"));
}

private static int getSpecSubString(String string) {
    Pattern pattern = Pattern.compile("[0-9]+$");
    Matcher matcher = pattern.matcher(string);

    if (matcher.find()) {
        String str = matcher.group();
        return Integer.parseInt(str);
    }

    return -1; // NO
}

答案 1 :(得分:0)

您可以使用

public static void main (String[] args) throws java.lang.Exception
{
        String sentence = "20 matches out of 568";
        String lastWord = sentence.replaceAll("^.*?(\\w+)\\W*$", "$1");
        System.out.println(lastWord);
}

没有正则表达式的另一种方式是

String[] all = data.split(" ");
System.out.println(all[all.length-1]);