How can I find int values within a string

Fraser Price picture Fraser Price · Jun 12, 2013 · Viewed 9k times · Source

I have a string, e.g. "ksl13<br>m4n", and I want to remove all non-digit characters in order to get the int 134.

Integer.parseInt(s) obviously isn't going to work, but not sure how else to go about it.

Answer

assylias picture assylias · Jun 12, 2013

You can use a regex first:

String s = "ksl13 m4n";
String clean = s.replaceAll("\\D+",""); //remove non-digits

Then you can use Integer.parseInt:

int i = Integer.parseInt(clean);

and i will be 134.