Extract digits from string - StringUtils Java
Use this code numberOnly will contain your desired output.
String str="sdfvsdf68fsdfsf8999fsdf09";
String numberOnly= str.replaceAll("[^0-9]", "");
I always like using Guava String utils or similar for these kind of problems:
String theDigits = CharMatcher.inRange('0', '9').retainFrom("abc12 3def"); // 123
Just one line:
int value = Integer.parseInt(string.replaceAll("[^0-9]", ""));
You can also use java.util.Scanner
:
new Scanner(str).useDelimiter("[^\\d]+").nextInt()
You can use next()
instead of nextInt()
to get the digits as a String
. Note that calling Integer.parseInt
on the result may be many times faster than calling nextInt()
.
You can check for the presence of number using hasNextInt()
on the Scanner
.
Use a regex such as [^0-9]
to remove all non-digits.
From there, just use Integer.parseInt(String);