Write Java program to Extract Numbers from the string
This Java program extracts numbers from a given input string by removing all non-numeric characters using the replaceAll() method of the String class.
- First, the program declares two strings str and num. The str variable will hold the input string that the user provides, while num will hold the extracted numeric characters from the input string.
- Then, the program creates a Scanner object to read input from the user. It prompts the user to enter the input string using the System.out.print() method and reads it into the str variable using the input.nextLine() method.
- Next, the program calls the replaceAll() method on the str variable, passing it the regular expression [^0-9] as the first argument. This regular expression matches all characters that are not digits from 0 to 9. The second argument to the replaceAll() method is an empty string, which replaces all non-numeric characters with nothing, effectively removing them from the string. The resulting string with only numeric characters is assigned to the num variable.
- Finally, the program outputs the extracted numeric characters using the System.out.println() method, along with a descriptive message.
Source Code
import java.util.Scanner;
class Extract_Numbers
{
public static void main(String[] args)
{
String str, num;
Scanner input = new Scanner(System.in);
System.out.print("Enter the Paragraphs : ");
str = input.nextLine();
num = str.replaceAll("[^0-9]", "");//extracting string
System.out.println("Numbers are : " + num);
}
}
Output
Enter the Paragraphs : Hello123 #World98
Numbers are : 12398