我有以下密码的正则表达式,可以在Password.123的在线正则表达式测试中正确评估:
/(?!^[0-9]*$)(?!^[a-z]*$)(?!^[A-Z]*$)(?!^[\\W]*$)(^[a-zA-Z0-9\\W]).{7,}/
当我在swift中创建NSRegularExpression时,它的计算结果不正确,无法找到Password.123的匹配项:
let password = "Password.123"
let regex = try! NSRegularExpression(pattern: "/(?!^[0-9]*$)(?!^[a-z]*$)(?!^[A-Z]*$)(?!^[\\W]*$)(^[a-zA-Z0-9\\W]).{7,}/", options: [])
let range = NSRange(location: 0, length: password.count)
print("Valid: \(regex.firstMatch(in: password, options: [], range: range) != nil)")
这打印错误但应该是真的。我哪里错了?
答案 0 :(得分:2)
从字符串中删除/
。即。
let regex = try! NSRegularExpression(pattern: "(?!^[0-9]*$)(?!^[a-z]*$)(?!^[A-Z]*$)(?!^[\\W]*$)(^[a-zA-Z0-9\\W]).{7,}", options: [])