Check NSString for special characters

后端 未结 5 2024
北恋
北恋 2020-12-23 09:39

I want to check an NSString for special characters, i.e. anything except a-z, A-Z and 0-9.

I don\'t need to check how many special characters are present, or their p

5条回答
  •  失恋的感觉
    2020-12-23 10:39

    NSCharacterSet * set = [[NSCharacterSet alphanumericCharacterSet] 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");
    }
    

提交回复
热议问题