Check if NSString is only letters

随声附和 提交于 2019-12-12 03:36:30

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!