How can I extract only the numeric values from the input string?
For example, the input string may be like this:
String str=\"abc d 1234567890pqr 548
You could split the string on spaces to get the individual entries, loop across them, and try to parse them with the relevant method on Integer
, using a try
/catch
approach to handle the cases where parsing it is as a number fails. That is probably the most straight-forward approach.
Alternatively, you can construct a regex to match only the numbers and use that to find them all. This is probably far more performant for a big string. The regex will look something like `\b\d+\b'.
UPDATE: Or, if this isn't homework or similar (I sort of assumed you were looking for clues to implementing it yourself, but that might not have been valid), you could use the solution that @npinti gives. That's probably the approach you should take in production code.