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.

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, above pattern will remove them as well. Consider below given 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:

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

 

Tags
Join 1000+ fellow learners! Enter your email address below: