This post will discuss how to remove certain characters from a String in Java.

1. Using String.replaceAll() method

The standard solution to replace each substring of a string that matches the given regular expression is using the String.replaceAll() method.

It can be used to remove certain characters from a String, as shown below. The following code replaces all matches of the regular expression \w with an empty string "". Note that \w is a predefined character class that denotes a word character [a-zA-Z_0-9].

Download  Run Code

Output:

HelloWorld_123

 
If you need to retain only a few characters, you can specify those characters after negation ^. For example, [^a-zA-Z] matches with any character except a to z and A to Z.

Download  Run Code

Output:

HelloWorld

2. Using String.replace() method

Here’s another solution that uses the String.replace() method to remove all occurrences of each character from the string within a loop. This method might perform relatively slower than the replaceAll() method.

Download  Run Code

Output:

Hello World123

3. Using Guava

If you prefer the Guava library, you can use its CharMatcher class for removing certain characters from a String. The idea is to get a char matcher that matches with any of the specified characters and remove all matching characters from the specified character set using the removeFrom() method. This is demonstrated below:

Download Code

Output:

Hello World123

 
Alternatively, you can use the retainFrom() method to retain all matching characters from the specified character set, as shown below:

Download Code

Output:

123

That’s all about removing certain characters from a String in Java.