检查字符串的所有字符是否都是大写,除了特殊符号

dan*_*mez 6 java regex

这是我第一次使用Java的Pattern类,因为我想检查字符串是否为大写.特殊符号如"." 和","应被视为大写.以下是预期结果:

"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
Run Code Online (Sandbox Code Playgroud)

我试图使用apache的StringUtils,但它不能这样工作..

Boz*_*zho 20

你可以查看:

if (str.toUpperCase().equals(str)) {..}
Run Code Online (Sandbox Code Playgroud)


Gli*_*ire 4

只需搜索,[a-z]如果找到则返回 false:

if (str.matches(".*[a-z].*")) { 
    // Negative match (false)
}
Run Code Online (Sandbox Code Playgroud)

或者,搜索^[^a-z]*$(不确定 Java 正则表达式语法,但基本上整个字符串不是小写字符):

if (str.matches("[^a-z]*")) { 
    // Positive match (true)
}
Run Code Online (Sandbox Code Playgroud)