Check if NSString contains alphanumeric + underscore characters only

后端 未结 7 1746
余生分开走
余生分开走 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:38

    You can create your own character set:

    NSCharacterSet *s = [NSCharacterSet characterSetWithCharactersInString:@"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890_"];
    

    Once you have that, you invert it to everything that's not in your original string:

    s = [s invertedSet];
    

    And you can then use a string method to find if your string contains anything in the inverted set:

    NSRange r = [string rangeOfCharacterFromSet:s];
    if (r.location != NSNotFound) {
      NSLog(@"the string contains illegal characters");
    }
    
    0 讨论(0)
提交回复
热议问题