我遇到简单的NSPredicates和正则表达式的问题:
NSString *mystring = @"file://questions/123456789/desc-text-here"; NSString *regex = @"file://questions+"; NSPredicate *regextest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex]; BOOL isMatch = [regextest evaluateWithObject:mystring];
在上面的示例isMatch
中,始终为false/NO.
我错过了什么?我似乎无法找到匹配的正则表达式file://questions
.
NSPredicates似乎尝试匹配整个字符串,而不仅仅是子字符串.您的尾随+
只是意味着匹配一个或多个's'字符.您需要允许匹配任何尾随字符.这有效:regex = @"file://questions.*"
如果你只是想测试字符串是否存在:试试这个
NSString *myString = @"file://questions/123456789/desc-text-here"; NSString *searchString = @"file://questions"; NSRange resultRange = [myString rangeWithString:searchString]; BOOL result = resultRange.location != NSNotFound;
改变地,使用谓词
NSString *myString = @"file://questions/123456789/desc-text-here"; NSString *searchString = @"file://questions"; NSPredicate *testPredicate = [NSPredicate predicateWithFormat:@"SELF BEGINSWITH %@", searchString]; BOOL result = [testPredicate evaluateWithObject:myString];
我相信文档声明使用谓词是检查子字符串是否存在时的方法.