所以我有以下代码:
func isValidPassword(password: String) -> Bool {
let pattern = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)[A-Za-z\\d]{2,}"
let regexText_1 = NSPredicate(format: "SELF MATCHES %@", pattern)
let result_1 = regexText_1.evaluate(with: password)
return result_1
}
print(isValidPassword(password: "3213aA")) \\ true
print(isValidPassword(password: "3213aA!")) \\ false
我需要检查至少一个大写字母,至少一个小写字母和至少一个数字。 我不介意有特殊字符。 我该如何实现?
非常感谢。
答案 0 :(得分:1)
也许你想要这个
let pattern = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)[A-Za-z\\d\\!]{2,}"
print(isValidPassword(password: "3213aA")) // true
print(isValidPassword(password: "3213aA!")) // true
说明:
[A-Za-z\\d\\!]
表示'A到Z'或'a到z'或'数字'或'!可能包含或不包含。
答案 1 :(得分:0)
您可以使用此功能来检查密码是否具有:
为使其更易于理解,它的划分方式如下:
func isValidPassword(password: String) -> Bool {
// Contains at least one upper case
let uppperCaseRegEx = ".*[A-Z]+.*"
let uppperCaseTest = NSPredicate(format:"SELF MATCHES %@", uppperCaseRegEx)
let uppperCaseTestResult = uppperCaseTest.evaluate(with: password)
// Contains at least one lower case
let lowerCaseRegEx = ".*[a-z]+.*"
let lowerCaseTest = NSPredicate(format:"SELF MATCHES %@", lowerCaseRegEx)
let lowerCaseTestResult = lowerCaseTest.evaluate(with: password)
// Contains a digit number
let numberRegEx = ".*[0-9]+.*"
let digitTest = NSPredicate(format:"SELF MATCHES %@", numberRegEx)
let digitTestResult = digitTest.evaluate(with: password)
return uppperCaseTestResult && lowerCaseTestResult && digitTestResult
}