How can we extract the numbers from an input string in Java?

JavaObject Oriented ProgrammingProgramming

The java.lang.String class gives a considerable measure of methods to deal with a string. By the assistance of these methods, one can perform operations on the string like trimming, concatenating, converting and comparing. We can extract the numbers from a given string by using the replaceAll() method of a String class.

Example

import java.util.Scanner;
public class StringExtractTest {
   public static void main(String[] args) {
      String input;
      String numbers;
      Scanner scanner = new Scanner(System.in);
      System.out.print(" Please enter a string from the keyboard that contains numbers: ");
      input = scanner.nextLine();
      numbers = input.replaceAll("[^0-9]", ""); 
      System.out.println("The Numbers are: " + numbers);
   }
}

Output

Please enter a string from the keyboard that contains numbers: Welcome to Tutorials Point 1234567890
The Numbers are: 1234567890
raja
Published on 30-Jul-2019 15:42:03
Advertisements