Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract digits from a string in Java

Tags:

java

string

I have a Java String object. I need to extract only digits from it. I'll give an example:

"123-456-789" I want "123456789"

Is there a library function that extracts only digits?

Thanks for the answers. Before I try these I need to know if I have to install any additional llibraries?

like image 201
user488469 Avatar asked Oct 09 '22 15:10

user488469


People also ask

How can I extract a number from a string in Java?

Java code to extract digits or numbers from a string with logic and explanation. We'll use 2 methods: (1) using regex expression with replaceAll method of String object, and (2) using loop and ascii values of characters.

How do you find the number of numerical digits in a string in Java?

isDigit(s. charAt(i)) will count the number of digits in the given string. 'Character. isDigit' will count the number of each digit in the string.


1 Answers

You can use regex and delete non-digits.

str = str.replaceAll("\\D+","");
like image 605
codaddict Avatar answered Oct 22 '22 19:10

codaddict