Skip to content

Java String keep only letters example

Java String keep only letters example shows how to keep only letters in String. The example also shows how to keep only lowercase letters, only uppercase letters and keep Unicode characters.

How to keep only letters in String in Java?

You can remove the non letter characters from the String using regular expression along with the replaceAll method of Java String class. We are going to use the “[^a-zA-Z]” regular expression pattern to keep only letters in a String where,

So our pattern “[^a-zA-Z]” means “not between a and z and not between A and Z”. We are going to replace all characters that match the pattern with the empty string. That will leave us only letters as given below.

Example

Output

As you can see from the output, we have removed all the non letter characters from the string.

How to keep only lowercase letters in String?

If you want to keep only lowercase letters in String, you can use the “[^a-z]” regular expression pattern with the replaceAll method as given below.

Output

How to keep only uppercase letters in String?

If you want to keep only uppercase letters in the String, you can use the “[^A-Z]” regular expression pattern with the replaceAll method as given below.

Output

How to keep Unicode letters/characters in String?

If your String contains Unicode characters, none of the above given patterns will keep them. Please see below given code snippet.

Output

To retain Unicode letters, we need to use the “\\pL” (with lowercase ‘p’) regular expression pattern that matches any Unicode letter along with the “^” symbol to denote negation. So the complete pattern will be “^\\pL” which means, “not matching with any Unicode letter”. We can also use the “\\PL” pattern (with uppercase ‘P’) which means “not Unicode character” as given below.

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.