我想知道如何使用NSPredicate评估满足两个条件的NSString。例如,如何检查一个字符串至少应该有一个大写字母和至少一个数字。
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 这里 进行更多检查。
这样做:
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];
我自己找到了解决方案。我使用了正则表达式和谓词来解决这个问题。
NSPredicate *pwdCheck = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", @"(?=.*?[A-Z])(?=.*?[0-9]).*"];
bool isValid = [pwdCheck evaluateWithObject:@"99a99A3w"];
感谢您的帮助