【问题标题】:NSPredicate Password FormatNSPredicate 密码格式
【发布时间】:2018-04-27 19:02:05
【问题描述】:

我正在尝试找出使用NSPredicate 验证密码字段的准确解决方案。这是我的代码:

-(int)checkPasswordStrength:(NSString *)password
{
    NSPredicate *validPassword = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",@"\\b^(?=.*[0-9]+?)(?=.*[A-Z]+?)(?=.*[a-z]*?)(?=.*[!@#$%?]+?)[0-9A-z!@#$%?]{8,20}$\\b"];
    NSString *escapedPassword = [NSRegularExpression escapedPatternForString:password];
    if(![validPassword evaluateWithObject:escapedPassword]) {
        [Helper showAlertWithTitle:@"" Message:@"Password should contain 8 to 20 alphanumeric characters, one capitalized letter, and with at least one of the symbols (e.g. !@#$%?)"];
        return 0;
    }

    return 1;
}

我已经尝试过这些模式:

\\b^(?=.*[0-9]+?)(?=(.*\\d){1})(?=.*[a-zA-Z])(?=.*[!@#$%?]).*[0-9a-zA-Z!@#$%?]{8,20}\\b

\\b^(?=.*[0-9]+?)(?=.*[A-Z]+?)(?=.*[a-z]*?)(?=.*[!@#$%?]+?)[0-9A-z!@#$%?]{8,20}$\\b

\\b^(?=.*[0-9]+?)(?=.*[A-Z]+?)(?=.*[a-z]*?)(?=.*[!@#$%?]+?)[0-9A-z!@#$%?]{8,20}$\\b

... without escapingescaping 字符串,但它不仅适用于这种类型的密码模式(其中特殊字符位于 first 和 last 密码字符串):

OverAndUnder21!
AreYouHere2?
PleaseDial9#
!4Ngrier!
!D4ngerZone

所有其他密码都有效:

P@MyF8fulDog
classM8s4L!fe

等等……

我尝试在 regex101.com 中测试我的 RegEx 模式,它似乎完全匹配。

NSPredicate 中允许特殊字符作为第一个和最后一个字符的正确验证模式是什么?

【问题讨论】:

  • 您的消费部分不允许?。尝试添加它并删除单词边界:^(?=.*[0-9])(?=.*[A-Z])(?=.*[a-z])(?=.*[!@#$%?])[0-9A-Za-z!@#$%?]{8,20}$
  • 感谢您的指出。我在问题和代码中添加了问号,但它仍然不接受最后一个字符作为特殊字符来验证密码。
  • 您是否删除了单词边界?见regex101.com/r/Y1d0u6/1
  • 是的,我确实删除了它。它现在工作正常。谢谢。

标签: objective-c regex nspredicate


【解决方案1】:

你需要去掉单词边界并在模式中添加一个问号:

@"^(?=.*[0-9])(?=.*[A-Z])(?=.*[a-z])(?=.*[!@#$%?])[0-9A-Za-z!@#$%?]{8,20}$"

请参阅regex demo

模式开头和结尾处的单词边界要求第一个和最后一个字符是单词字符(字母、数字或_)。

另外,请注意 +? 在前瞻中不是必需的,因为您只需要至少 1 个模式实例。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多