David David - 6 months ago 8
Java Question

How to get an Integer from a String (contains letters and number)?

Here is an example of what I'm trying to do:

String letternumber = "Example - 123";


I want to output
"123"
but I need to get it from the string, I can't just do:

String number = "123";
System.out.println(Integer.parseInt(number));


Or I will get an error.

Answer

You need to use Pattern and Matcher Classes.

String s = "Example - 123";
Matcher m = Pattern.compile("\\d+").matcher(s);
while(m.find())
{
        int num = Integer.parseInt(m.group());
        System.out.println(num);
}

Output:

123
Comments