Signup/Sign In

How to Remove Numeric values from String

In this post, we are going to remove numeric values from the string using Java code. String in Java is a sequence of characters enclosed within double quotes (" ").

A string can contain numbers, alphabets, and special symbols. Therefore sometimes we need to filter the string to get alphabets only. Suppose we have some user names that contain alphanumeric values then to get a valid user name we need to filter them by removing other characters.

Here, we using the replaceAll() method that takes two arguments, one is the regex to filter the string, and the second is the replacement string.

The regex can be any valid regular expression to remove the characters from the string.

Time for an Example

Let's create an example to remove numeric values from a string. Here, we are using the replaceAll() method and a regex ['^A-Za-z'] to retain alphabets only in the string.

public class Main {
	public static void main(String[] args){
		String str = "House123sector4";
		System.out.println(str);
		// Replacing 
		str = str.replaceAll("[^A-Za-z]", "");
		System.out.println("String only:");
		System.out.println(str);
	}
}


House123sector4
String only:
Housesector

Example 1

Let's take another example to remove numeric values from a string. Here we are using "\\d" as a regex to remove all digits from the string and get the result.

public class Main {
	public static void main(String[] args){
		String str = "House123sector4";
		System.out.println(str);
		// Replacing 
		str = str.replaceAll("\\d", "");
		System.out.println("String only:");
		System.out.println(str);
	}
}


House123sector4
String only:
Housesector

Example 2

In this example, we passed a regex [0-9] to the replaceAll() method that returns a string after removing all the digits or numerical value. See the example below.

public class Main {
	public static void main(String[] args){
		String str = "House123sector4";
		System.out.println(str);
		// Replacing 
		str = str.replaceAll("[0-9]", "");
		System.out.println("String only:");
		System.out.println(str);
	}
}


House123sector4
String only:
Housesector



About the author:
I am a 3rd-year Computer Science Engineering student at Vellore Institute of Technology. I like to play around with new technologies and love to code.