Java String Handling RegEx

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. Example also shows how to remove all special characters from String in Java.

How to keep only letters and numbers in String in Java?

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

In order to do that, we are going to use “[^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 replaceAll method of String class as given below.


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


How to keep Unicode characters?

If your string contains Unicode characters, above pattern will remove them as well. Consider below given example string and its 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.


See Also:

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


About the author



rahimv has over 15 years of experience in designing and developing Java applications. His areas of expertise are J2EE and eCommerce. If you like the website, follow him on Facebook, Twitter or Google Plus.

Add Comment

Your email address will not be published. Required fields are marked *