我输入的用户名只需要输入a-z和A-Z。我想验证这个名字,请帮助我。
提前致谢
答案 0 :(得分:4)
NSCharacterSet *nonAlphabetChars = [[NSCharacterSet characterSetWithCharactersInString:@"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"] invertedSet];
if ([myString rangeOfCharacterFromSet:nonAlphabetChars].location == NSNotFound) {
// myString is valid
...
} else {
// myString contains at least one invalid character
...
}
答案 1 :(得分:1)
你可以这样做:
NSCharacterSet *allowed = [NSCharacterSet alphanumericCharacterSet];
NSCharacterSet *forbidden = [allowed invertedSet];
NSRange range = [string rangeOfCharacterFromSet:forbidden];
BOOL isValid = (range.location == NSNotFound);
alphanumericCharacterSet
可能不完全符合您的要求,有关更多选项,请参阅NSCharacterSet
。