Get all digits from a string in Java


Let’s say the following is our string.

String str = "DEMO98 TE4567XT";

To display only the digits from the above string, we have used the replaceAll() method and replace all the characters with empty.

str.replaceAll("\D", ""))

The following is the final example that displays only digits from the string.

Example

 Live Demo

public class Demo {
   public static void main(String[] args) {
      String str = "DEMO98 TE4567XT";
      System.out.println("String = "+str);
      System.out.println("Displaying digits: "+str.replaceAll("\D", ""));
 }
}

Output

String = DEMO98 TE4567XT
Displaying digits: 984567

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 26-Jun-2020

513 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements