检查NSString的特殊字符 [英] Check NSString for special characters
问题描述
我想检查NSString是否包含特殊字符,即az,AZ和0-9以外的任何字符。
I want to check an NSString for special characters, i.e. anything except a-z, A-Z and 0-9.
我不需要检查多少特殊字符存在或它们的位置,我只需要知道一个特定的字符串是否包含任何或。
I don't need to check how many special characters are present, or their positions, I just need to know whether a particular string contains any or not. If it does, then I want to be able to display "Error!", or something similar.
例如, jHfd9982 可以显示错误! asdJh992 @ 不是。
For example, jHfd9982 is OK but asdJh992@ is not.
此外,不允许使用重音符号,变音符号等字母。
Also, letters with accents, diacritical, etc. should not be allowed.
我该如何解决这个问题?
How would I go about this?
谢谢!
>
推荐答案
NSCharacterSet * set = [[NSCharacterSet characterSetWithCharactersInString:@"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLKMNOPQRSTUVWXYZ0123456789"] invertedSet];
if ([aString rangeOfCharacterFromSet:set].location != NSNotFound) {
NSLog(@"This string contains illegal characters");
}
您还可以使用regex(此语法来自RegexKitLite: http://regexkit.sourceforge.net ):
You could also use a regex (this syntax is from RegexKitLite: http://regexkit.sourceforge.net ):
if ([aString isMatchedByRegex:@"[^a-zA-Z0-9]"]) {
NSLog(@"This string contains illegal characters");
}
这篇关于检查NSString的特殊字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!