Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if all characters of a string is uppercase except special symbols

Tags:

java

regex

It's my first time to use the Pattern class of Java because I want to check a string if it is in uppercase. Special symbols like "." and "," should be treated as Uppercase. Here are the expected results:

"test,." should return false //because it has a lowercase character
"TEST,." should return true //because all are uppercase and the special characters
"test" should return false //because it has a lowercase character
"TEST" should return true //because all are uppercase
"teST" should return false //because it has a lowercase character

I tried to use the StringUtils of apache but it doesn't work this way..

like image 764
dgzz Avatar asked Nov 22 '13 13:11

dgzz


3 Answers

You can check:

if (str.toUpperCase().equals(str)) {..}
like image 172
Bozho Avatar answered Oct 21 '22 12:10

Bozho


Just search for [a-z] then return false if it's found:

if (str.matches(".*[a-z].*")) { 
    // Negative match (false)
}

Alternatively, search for ^[^a-z]*$ (not sure on Java regex syntax, but basically whole string is not lowercase characters):

if (str.matches("[^a-z]*")) { 
    // Positive match (true)
}
like image 33
Glitch Desire Avatar answered Oct 21 '22 13:10

Glitch Desire


You could iterate through the chars. It has the advantage that you can customize the matching as you wish.

boolean ok = true;
for(char c : yourString.toCharArray()) {
    if(Character.isLetter(c) && !Character.isUpperCase(c)) {
        ok = false;
        break;
    }
}
// ok contains your return value
like image 42
MightyPork Avatar answered Oct 21 '22 13:10

MightyPork