Java String Handling RegEx

Java String keep only letters example

Java String keep only letters example shows how to keep only letters in String. 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 non letter characters from String using regular expression along with the replaceAll method of Java String class. We are going to use “[^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 matches with the pattern with empty string. That will leave us only letters as given below.

Java String keep only letters example

Output

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

How to keep only lowercase letters in String in Java?

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

Output

How to keep only uppercase letters in String in Java?

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

Output

How to keep Unicode letters/characters in String in Java?

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

Output

To retain Unicode letters, we need to use “\\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 “\\PL” pattern (with uppercase ‘P’) which means “not Unicode character” as given below.

Output

See Also:

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

 

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