David
David

Reputation: 177

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.

Upvotes: -3

Views: 1439

Answers (1)

Avinash Raj
Avinash Raj

Reputation: 174706

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

Upvotes: 0

Related Questions