Get all digits from a string in Java

Java 8Object Oriented ProgrammingProgramming

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
raja
Published on 12-Dec-2018 07:37:39
Advertisements