检查 Java 包含一个字母和数字字符以及这些特殊字符之一(@、#、$)的字符串

Check Java String containing one alpha & numeric characters and one of these special characters(@, #,$)

您好,我想检查一个字符串是否包含一个字母、一个数字和至少一个这些特殊字符(@、#、$)。那么谁能指导我解决这个问题。

注意:我有 apache common lang 3.0 库。它会帮助我们解决上述问题吗?

您可以使用 String.matches() 并使用正则表达式来执行此操作。考虑以下解决方案。

public boolean isAlphaNumeric(String s){
String pattern= "^(?=.*[a-zA-Z])(?=.*\d)(?=.*[!@#$*()_+])[A-Za-z\d][A-Za-z\d!@#$*()_+]";
    if(s.matches(pattern)){
        return true;
    }
    return false;   

}

如果有效请告诉我。

这是一个简单的实现。

private static boolean isValidPassword(char[] password) {
    boolean hasLetter = false, hasDigit = false, hasSpecial = false;
    for (char ch : password)
        if (Character.isLetter(ch))
            hasLetter = true;
        else if (Character.isDigit(ch))
            hasDigit = true;
        else if ("@#$".indexOf(ch) != -1)
            hasSpecial = true;
    return (hasLetter && hasDigit && hasSpecial);
}

我可以根据需要调整 "letter"、"digit" 和 "special" 的确切定义,并在找到所有 3 个时尽早停止搜索,如果需要的话。