This post will discuss how to remove all non-alphanumeric characters from a String in Java.

1. Using String.replaceAll() method

A common solution to remove all non-alphanumeric characters from a String is with regular expressions. The idea is to use the regular expression [^A-Za-z0-9] to retain only alphanumeric characters in the string.

Download  Run Code

Output:

ABCDE1

 
You can also use [^\w] regular expression, which is equivalent to [^a-zA-Z_0-9]. It will replace characters that are not present in the character range A-Z, a-z, 0-9, _. Alternatively, you can use the character class \W that directly matches with any non-word character, i.e., [a-zA-Z_0-9].

Download  Run Code

Output:

ABCD_E1

 
Note, this solution retains the underscore character. If you need to remove underscore as well, you can use regex [\W]|_. Alternatively, you can use the POSIX character class \p{Alnum}, which matches with any alphanumeric character [A-Za-z0-9]. It is equivalent to [\p{Alpha}\p{Digit}].

Download  Run Code

Output:

ABCDE1

2. Using Guava

If you use the Guava library in your project, you can use its javaLetterOrDigit() method from CharMatcher class to determine whether a character is an alphabet or a digit. You can remove or retain all matching characters returned by javaLetterOrDigit() method using the removeFrom() and retainFrom() method respectively. This is demonstrated below:

Download Code

Output:

ABCDE1

 
You can also specify the range of characters to be removed or retained in a String using the static method inRange() of the CharMatcher class.

Download Code

Output:

ABCDE1

That’s all about removing all non-alphanumeric characters from a String in Java.