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";
}
請注意,此答案假定您只想允許這些特殊字符,而在輸出中不允許使用其他字母數字字符。
添加回答
舉報