Check whether an NSString contains a special character and a digit

前端 未结 5 1613
别那么骄傲
别那么骄傲 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:09

    Without any additional frameworks:

    NSCharacterSet * set = [[NSCharacterSet characterSetWithCharactersInString:@"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"] invertedSet];
    
    if ([aString rangeOfCharacterFromSet:set].location != NSNotFound) {
        NSLog(@"This string contains illegal characters.");
    }
    

    You could also use a regex (this syntax is from RegexKitLite: http://regexkit.sourceforge.net):

    if ([aString isMatchedByRegex:@"[^a-zA-Z0-9]"]) {
        NSLog(@"This string contains illegal characters.");
    }
    

提交回复
热议问题