The following example shows how you can use the replaceAll() method to extract all digits from a string in Java: // string contains numbers String str = "The price of the book is $49"; // extract digits only from strings String numberOnly = str. replaceAll("[^0-9]", ""); // print the digitts System. out.
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);
try this :
String s = "helloThisIsA1234Sample";
s = s.replaceAll("\\D+","");
This means: replace all occurrences of digital characters (0 -9) by an empty string !
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With