Check whether an NSString contains a special character and a digit

前端 未结 5 1578
别那么骄傲
别那么骄傲 2020-12-31 18:56

I need to check whether a string contains one uppercase letter, one lower case letter, one integer and one special character. How do I check?

5条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2020-12-31 19:14

    Maulik's answer is incorrect. That will check for anything OTHER than any alphanumeric character, but doesn't enforce that there be one uppercase letter, one lowercase letter, and one integer. You do in fact have to do 3 checks to verify each constraint.

    NSCharacterSet *lowerCaseChars = [NSCharacterSet characterSetWithCharactersInString:@"abcdefghijklmnopqrstuvwxyz"];
    
    NSCharacterSet *upperCaseChars = [NSCharacterSet characterSetWithCharactersInString:@"ABCDEFGHIJKLKMNOPQRSTUVWXYZ"];
    
    NSCharacterSet *numbers = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
    
    if ([aString rangeOfCharacterFromSet:lowerCaseChars].location == NSNotFound || [aString rangeOfCharacterFromSet:upperCaseChars].location = NSNotFound || [aString rangeOfCharacterFromSet:numbers].location == NSNotFound) {
     NSLog(@"This string contains illegal characters");
    }
    

提交回复
热议问题