问题
What's the best way to make sure an NSString contains only the letters a-z and A-Z.
I've tried the following code but it's not working for some reason:
NSString *myegex = @"[A-Za-z]";
NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", myregex];
if (![emailTest evaluateWithObject:self.initials.text]) {
// print error
return;
}
回答1:
You can do it in a simpler way by creating your own NSCharacterSet then checking the string against that set with rangeOfCharacterFromSet:
//Create character set
NSCharacterSet *validChars = [NSCharacterSet characterSetWithCharactersInString:@"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"];
//Invert the set
validChars = [validChars invertedSet];
//Check against that
NSRange range = [myString rangeOfCharacterFromSet:validChars];
if (NSNotFound != range.location) {
//invalid chars found
}
回答2:
I'm not sure how Objective-C regex engine works, but you can leverage anchors ^ and $ to check if your string starts and finishes with letters by using this regex:
^[A-Za-z]+$
Using your code, would be:
NSString *myegex = @"^[A-Za-z]+$";
NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", myregex];
if (![emailTest evaluateWithObject:self.initials.text]) {
// print error
return;
}
来源:https://stackoverflow.com/questions/30699407/check-if-nsstring-is-only-letters