NSPredicate - 评估两个条件

时间:2013-12-10 06:26:17

标签: iphone objective-c regex nspredicate

我想知道如何使用NSPredicate评估满足两个条件的NSString。例如,如何检查应至少包含一个大写字母和至少一个数字的字符串。

3 个答案:

答案 0 :(得分:1)

您可以将ANDing用于两个或更多条件。

 NSManagedObjectContext *context = [appDelegate managedObjectContext];
 NSEntityDescription *entityDescription = [NSEntityDescription entityForName:entityName inManagedObjectContext:context];
 NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
[fetchRequest setEntity:entityDescription];

 NSPredicate *predicate = [NSPredicate predicateWithFormat:@"fbUID = %@ AND birthDate = %d AND birthMonth = %d AND greetingYear = %d", uID, birthDate, birthMonth, greetingYear];

//NSLog(@"%@ :",predicate);
[fetchRequest setPredicate:predicate];

 NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];

您可以查看有关NSPredicate HERE的更多信息。

答案 1 :(得分:1)

一种方法是:

NSCharacterSet *upperCaseCharacters = [NSCharacterSet characterSetWithCharactersInString:@"ABCDEFGHIJKLKMNOPQRSTUVWXYZ"];
NSCharacterSet *numbers = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];

NSPredicate *predicate = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {

    return ([evaluatedObject rangeOfCharacterFromSet:upperCaseCharacters].location != NSNotFound && [evaluatedObject rangeOfCharacterFromSet:numbers].location != NSNotFound);

}];

NSString *stringToEvaluate = @"aasad5D";

BOOL result = [predicate evaluateWithObject:stringToEvaluate];

另一个解决方案是复合谓词,请参阅此问题,例如如何使用复合谓词create a Compound Predicate in coreData xcode iphone

答案 2 :(得分:0)

我自己找到了解决方案。我使用带谓词的正则表达式来解决这个问题。

NSPredicate *pwdCheck = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", @"(?=.*?[A-Z])(?=.*?[0-9]).*"];
bool isValid = [pwdCheck evaluateWithObject:@"99a99A3w"];

感谢您的帮助