3 回答

TA贡献1829条经验 获得超13个赞
尝试这个:
private final Pattern hasSpecialChar = Pattern.compile("[^A-Za-z0-9!@#$%^&*]+");
if (hasSpecialChar.matcher(password).find()) {
return "String allows only !@#$%^&* special characters";
}

TA贡献1859条经验 获得超6个赞
Mabe 下面的代码片段将帮助您:
private final Pattern hasSpecialChar = Pattern.compile("[^!@#$%^&*]");
if (hasSpecialChar.matcher(password).find()) {
return "String allows only !@#$%^&* special characters";
}

TA贡献1951条经验 获得超3个赞
您的代码片段正在查看特殊字符是否至少出现一次。
对此的一个简单修正是否定检查——即寻找至少一个不在可接受字符集中的非特殊字符:
private final Pattern hasSpecialChar = Pattern.compile("[^!@#$%^&*]");
if (hasSpecialChar.matcher(password).find()) {
return "String allows only !@#$%^&* special characters";
}
请注意,此答案假定您只想允许这些特殊字符,而在输出中不允许使用其他字母数字字符。
添加回答
举报