get Last Int inside a string using regular expression - Java java.util.regex

Java examples for java.util.regex:Match Number

Description

get Last Int inside a string using regular expression

Demo Code


//package com.java2s;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
    public static void main(String[] argv) {
        String str = "123 321 1234";
        System.out.println(getLastInt(str));
    }/*from  w ww  .j  a va  2 s .  c o m*/

    static final Pattern NUM_PATTERN = Pattern.compile(".*?(\\d+)");

    public static int getLastInt(String str) {
        Matcher matcher = NUM_PATTERN.matcher(str);
        if (matcher.matches()) {
            return Integer.parseInt(matcher.group(1));
        } else {
            throw new NumberFormatException();
        }
    }
}

Related Tutorials