Skip to content

Java String keep only letters and numbers example

Java String keep only letters and numbers example shows how to keep only letters and numbers in String. The example also shows how to remove all special characters from String in Java.

How to keep only letters and numbers in String?

You can match any character, which is not a letter or a number using the regular expression in Java. You can then remove them using the replaceAll method of Java String class.

In order to do that, we are going to use the “[^a-zA-Z0-9]” regular expression pattern where,

So our overall pattern “[^a-zA-Z0-9]” means “not any upper or lower case letter and number”. Once we match these characters, we will replace them with the empty string using the replaceAll method of the String class as given below.

Output

If you want to keep spaces, you can add “\\s” to our pattern to keep them.

Output

How to keep Unicode characters?

If your string contains Unicode characters, the above given pattern will remove them as well. Consider this example string and its output.

Output

As you can see from the output, all Unicode characters are removed from the string. If you want to keep Unicode characters, you need to use “[^\\pL\\pN\\s]” pattern instead where,

Therefore, our pattern means, “match any character which is not Unicode letter, Unicode number or space character”. Here is the final code snippet.

Output

See Also:

This example is a part of the Java String tutorial and Java RegEx tutorial.

Please let me know your views in the comments section below.

About the author

Leave a Reply

Your email address will not be published.