开发者

How to check if a string contains English letters (A-Z)?

How can I check whether a string contains the English Letters (A through Z) in Objective-开发者_JAVA百科C? In PHP, there is preg_match method for that.


One approach would be to use regular expressions — the NSRegularExpression class. The following demonstrates how you could detect any English letters, but the pattern could be modified to match only if the entire string consists of such letters. Something like ^[a-zA-Z]*$.

NSRegularExpression *regex = [[[NSRegularExpression alloc]
  initWithPattern:@"[a-zA-Z]" options:0 error:NULL] autorelease];

// Assuming you have some NSString `myString`.
NSUInteger matches = [regex numberOfMatchesInString:myString options:0
  range:NSMakeRange(0, [myString length])];

if (matches > 0) {
  // `myString` contains at least one English letter.
}

Alternatively, you could construct an NSCharacterSet containing the characters you're interested in and use NSString's rangeOfCharacterFromSet: to find the first occurrence of any one. I should note that this method only finds the first such character in the string. Maybe not what you're after.

Finally, I feel like you could do something with encodings, but haven't given this much thought. Perhaps determine if the string could be represented using ASCII (using canBeConvertedToEncoding:) and then check for numbers/symbols?

Oh, and you could always iterate over the string and check each character! :)


You can use simple NSPredicate test.

NSString *str = @"APPLE";
NSString *regex = @"[A-Z]+"; 
NSPredicate *test = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex]; 
BOOL result = [test evaluateWithObject:str];


You could also use NSCharacterSet and use the rangeOfCharacterFromSet: method to see if the returned NSRange is the entire range of the string. characterSetWithRange would be a good place to start to create your characterSet.


You can use the NSRegularExpression Class (Apple's documentation on the class can be viewed here)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜