Java Data Type How to - Extract Integer Part in String








Question

We would like to know how to extract Integer Part in String.

Answer

import java.util.regex.Pattern;
import java.util.regex.Matcher;
//from  w ww  .j  a  v a2 s . c  om
public class Main {

    public static void main(String[] args) {
        String input = "Hello123";
        int output = extractInt(input);

        System.out.println("input [" + input + "], output [" + output + "]");
    }
    public static int extractInt(String str) {
        Matcher matcher = Pattern.compile("\\d+").matcher(str);

        if (!matcher.find())
            throw new NumberFormatException("For input string [" + str + "]");

        return Integer.parseInt(matcher.group());
    }
}