-3

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.

Mark Cidade
  • 98,437
  • 31
  • 224
  • 236
David
  • 179
  • 1
  • 1
  • 10

1 Answers1

0

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
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
  • Hi Avinash, I tried using the Pattern and Matcher classes, but a problem I encountered was that since I am loading the names of non-player characters in my game, and some of them have one word names, some have up to 4 word names, that it wouldn't work because the group number would be different for each non-player character name I want to select. The number I am trying to get from the String is their ID. Edit: I see you edited your response, maybe I was using it completely wrong. I will try this. Thanks, you helped me earlier too. :) – David Feb 14 '15 at 02:11
  • post an example along with expected output. – Avinash Raj Feb 14 '15 at 02:12
  • 1
    Providing incomplete information gets you an incomplete answer. – FlyingGuy Feb 14 '15 at 02:16
  • @Avinash Raj Thank you so much!! It worked. I think I will look further into these Classes. They are extremely useful. – David Feb 14 '15 at 02:17