1. Introduction

Sometimes, while dealing with strings in Java, we might need to remove all the non-numeric characters and retain only the numeric ones. This can be useful in various scenarios such as data preprocessing, input validation, and more. In this blog post, we will learn how to remove non-numeric characters from a string in Java using regular expressions.

2. Program Steps

1. Define the input string containing numeric and non-numeric characters.

2. Use the replaceAll() method along with a regular expression to remove all non-numeric characters from the string.

3. Print the modified string.

3. Code Program

public class RemoveNonNumericCharacters {

    public static void main(String[] args) {
        // Step 1: Define the input string containing numeric and non-numeric characters
        String inputString = "Java123 is 456awesome789!";

        // Step 2: Use the replaceAll() method and a regular expression to remove all non-numeric characters from the string
        String numericString = inputString.replaceAll("[^0-9]", "");

        // Step 3: Print the modified string
        System.out.println("Original String: " + inputString);
        System.out.println("Numeric String : " + numericString);
    }
}

Output:

Original String: Java123 is 456awesome789!
Numeric String : 123456789

4. Step By Step Explanation

– In Step 1, we define the inputString which contains a mixture of numeric and non-numeric characters.

– For Step 2, we employ the replaceAll() method of the String class. This method takes two parameters: the regular expression defining the characters to be replaced, and the string to replace them with. In this case, the regular expression "[^0-9]" is used to match any character that is not a digit between 0 and 9, and we replace these non-numeric characters with an empty string, effectively removing them.

– Finally, in Step 3, we print the originalString and the modified numericString to the console, demonstrating that all non-numeric characters have been successfully removed from the original string.