【问题标题】:NSPredicate regex not workingNSPredicate 正则表达式不起作用
【发布时间】:2012-10-10 14:02:59
【问题描述】:

我正在使用:

+ (BOOL)isPassword:(NSString*)password {
    NSString* pattern = @"^(?=.{6,20}$).*$";
    NSPredicate* predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
    return [predicate evaluateWithObject:password];
}

但它返回的是 ""。有什么建议吗?

【问题讨论】:

    标签: objective-c ios regex cocoa-touch nspredicate


    【解决方案1】:

    正如@Pfitz 指出的那样,您没有SELF。例如,在过滤数组时使用它。

    尝试改用NSRegularExpression

    NSError *error = nil;
    NSRegularExpression *regex = [NSRegularExpression 
                                  regularExpressionWithPattern:@"^(?=.{6,20}$).*$" 
                                  options:NSRegularExpressionCaseInsensitive 
                                    error:&error];
    NSTextCheckingResult *match = [regex firstMatchInString:password 
                                                    options:0
                                                      range:NSMakeRange(0, [password length])];
    if (match) {
        NSRange range = [match range];
        if (range.location != NSNotFound) {
            // match
        }
    }
    

    【讨论】:

    • 我不能,它不兼容 iOS 4。
    • 它兼容iOS 4,这里是正确的链接:developer.apple.com/library/ios/#documentation/Foundation/…
    • 顺便说一句:如果要求 iOS,你应该用 iOS 标记你的问题……
    • 感谢 iOS 链接 @vikingosegundo。更新了我的答案。
    • 我会的。顺便说一句,我的意思是与 iOS 3.x 兼容。我的错。但我喜欢你的代码,我会在不需要它在 3.x 中工作时使用它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-08
    • 2015-06-19
    相关资源
    最近更新 更多