Check if NSString contains alphanumeric + underscore characters only

后端 未结 7 1755
余生分开走
余生分开走 2021-01-30 00:52

I\'ve got a string that needs to be only a-z, 0-9 and _

How do I check if the input is valid? I\'ve tried this but it accepts letter like å,ä,ö,ø etc.

NS         


        
7条回答
  •  不知归路
    2021-01-30 01:22

    Some more easy way,

    NSMutableCharacterSet *allowedSet = [NSMutableCharacterSet characterSetWithCharactersInString:@"_"];
    [allowedSet formUnionWithCharacterSet:[NSCharacterSet alphanumericCharacterSet]];
    NSCharacterSet *forbiddenSet = [allowedSet invertedSet];
    

    It'll combine alphanumeric along with _underscore.

    you can use it like,

    NSRange r = [string rangeOfCharacterFromSet:forbiddenSet];
    if (r.location != NSNotFound) {
      NSLog(@"the string contains illegal characters");
    }
    

    PS. example copied from @DaveDeLong example :)

提交回复
热议问题