objective-c 如何检查目标 C 中的字符串是否仅包含字母数字字符?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1671605/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check if a string only contains alphanumeric characters in objective C?
提问by Cheng Lai
I'm working on a small iphone project and i would need to check if the userName entered only contains alphanumerical characters? (A-Z, a-z, 0-9. How would i go about checking it?
我正在处理一个小型 iphone 项目,我需要检查输入的用户名是否只包含字母数字字符?(A-Z, a-z, 0-9. 我将如何去检查它?
回答by Jason Harwig
If you don't want to bring in a regex library for this one task...
如果您不想为这项任务引入正则表达式库...
NSString *str = @"aA09";
NSCharacterSet *alphaSet = [NSCharacterSet alphanumericCharacterSet];
BOOL valid = [[str stringByTrimmingCharactersInSet:alphaSet] isEqualToString:@""];
回答by NSResponder
This will work:
这将起作用:
@implementation NSString (alphaOnly)
- (BOOL) isAlphaNumeric
{
NSCharacterSet *unwantedCharacters =
[[NSCharacterSet alphanumericCharacterSet] invertedSet];
return ([self rangeOfCharacterFromSet:unwantedCharacters].location == NSNotFound);
}
@end
回答by Soviut
You can use this regular expression libraryfor ObjectiveC. Use the following regex to match:
您可以将此正则表达式库用于 ObjectiveC。使用以下正则表达式进行匹配:
^[a-zA-Z0-9]*$
回答by JosephH
The NSCharacterSetbased answers do not give the results you might expect for Japanese etc text, often claiming that they do contain alphanumeric characters - the test being performed boils down to 'are there only letters or numbers', and Japanese (etc) characters count as 'Letters'.
在NSCharacterSet基于答案不给你所期望的日本等文本的结果,往往声称他们不包含字母数字字符-被执行的测试归结为“在那里只有字母或数字”,以及日本(等)字符算作“字母”。
If you're trying to check Latin characters vs a foreign language (eg. Japanese), then the answer from " How to determine if an NSString is latin based?" may help:
如果您正在尝试检查拉丁字符与外语(例如日语),那么“如何确定 NSString 是否基于拉丁语?”的答案可能会有所帮助:
BOOL isLatin = [myString canBeConvertedToEncoding:NSISOLatin1StringEncoding];
NSASCIIStringEncodingcould also be used instead of NSISOLatin1StringEncoding to further restrict the valid characters. You could also test using NSCharacterSet afterwards, to exclude special characters like !, #, etc.
NSASCIIStringEncoding也可以用来代替 NISOLatin1StringEncoding 来进一步限制有效字符。您还可以在之后使用 NSCharacterSet 进行测试,以排除诸如 !、# 等特殊字符。
回答by Jon Shier
I've run some rather extensive performance testing and there are several considerations to take into account when choosing how to validate your alphanumeric strings. First, of course, is that you may not even care about performance. If your app rarely validates strings, or perhaps even only does it once, whatever method that gives you the behavior you want is fine. Beyond that, here are my performance results.
我进行了一些相当广泛的性能测试,在选择如何验证字母数字字符串时需要考虑几个因素。首先,当然,您可能甚至不关心性能。如果您的应用程序很少验证字符串,或者甚至可能只验证一次,那么任何可以为您提供所需行为的方法都可以。除此之外,这是我的表现结果。
For custom character sets (say alphanumeric characters, without Unicode characters or marks), this is fastest for an initial run:
对于自定义字符集(比如字母数字字符,没有 Unicode 字符或标记),这是初始运行最快的:
NSCharacterSet *alphanumericSet = [NSCharacterSet characterSetWithCharactersInString:@"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"];
NSString *result = [self stringByTrimmingCharactersInSet:alphanumericSet];
return [result isEqualToString:@""];
If you're okay using a precomputed character set like [NSCharacterSet alphanumericCharacterSet]then this was fastest:
如果您可以使用预先计算的字符集,[NSCharacterSet alphanumericCharacterSet]那么这是最快的:
NSCharacterSet *alphanumericSet = [NSCharacterSet alphanumericCharacterSet];
alphanumericSet = alphanumericSet.invertedSet;
NSRange range = [self rangeOfCharacterFromSet:alphanumericSet];
return (range.location == NSNotFound);
Caching the character set in a static variable using dispatch_oncecan help quite a bit if you run these validations repeatedly. In that case, if you're certain you can absorb the initial compilation time, using a regex actually turns out to be the fastest for custom character sets:
dispatch_once如果您重复运行这些验证,使用缓存在静态变量中的字符集会很有帮助。在这种情况下,如果您确定可以吸收初始编译时间,那么使用正则表达式实际上对于自定义字符集来说是最快的:
static NSRegularExpression *alphanumericRegex;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
alphanumericRegex = [NSRegularExpression regularExpressionWithPattern:@"^[a-zA-Z0-9]*$" options:NSRegularExpressionCaseInsensitive error:nil];
});
NSUInteger numberOfMatches = [alphanumericRegex numberOfMatchesInString:self options:0 range:NSMakeRange(0, self.length)];
return (numberOfMatches == 1);
If you don't wish to use the regex, the custom set version of the cached rangeOfCharacterFromSetedges out the cached stringByTrimmingCharactersInCharacterSet:method:
如果您不想使用正则表达式,缓存的自定义集版本会rangeOfCharacterFromSet超出缓存stringByTrimmingCharactersInCharacterSet:方法:
static NSCharacterSet *alphanumericSet;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
alphanumericSet = [NSCharacterSet characterSetWithCharactersInString:@"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"];
alphanumericSet = alphanumericSet.invertedSet;
});
NSRange range = [self rangeOfCharacterFromSet:alphanumericSet];
return (range.location == NSNotFound);
For precomputed sets, the cached rangeOfCharacterFromSet:method was again the fastest:
对于预先计算的集合,缓存rangeOfCharacterFromSet:方法再次是最快的:
static NSCharacterSet *alphanumericSet;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
alphanumericSet = [NSCharacterSet alphanumericCharacterSet];
alphanumericSet = alphanumericSet.invertedSet;
});
NSRange range = [self rangeOfCharacterFromSet:alphanumericSet];
return (range.location == NSNotFound);
And for everyone's information, the isSupersetOfSet:method was the slowest, whether cached or not. Looks like isSupersetOfSet:is pretty slow.
对于每个人的信息isSupersetOfSet:,无论是否缓存,该方法都是最慢的。看起来isSupersetOfSet:很慢。
NSCharacterSet *stringSet = [NSCharacterSet characterSetWithCharactersInString:self];
NSCharacterSet *alphanumericSet = [NSCharacterSet alphanumericCharacterSet];
return [alphanumericSet isSupersetOfSet:stringSet];
I didn't do any testing of the underlying CFCharacterSet functions.
我没有对底层 CFCharacterSet 函数进行任何测试。
回答by Abhinav Singh
- (BOOL)isAlphaNumeric
{
NSCharacterSet *s = [NSCharacterSet characterSetWithCharactersInString:@"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'. "];
s = [s invertedSet];
NSRange r = [self rangeOfCharacterFromSet:s];
if (r.location == NSNotFound) {
return NO;
} else {
return YES;
}
}
Has the flexibility to add/ subtract new characters like whitespaces
可以灵活地添加/减去空格等新字符
P.S This method can be copy/paste in NSString category
PS 这个方法可以在 NSString 类中复制/粘贴
回答by Adrian
I really like the RegexKitLiteFramework. It uses the ICU regex library, which is already included with OSX and is unicode-safe.
我真的很喜欢RegexKit Lite框架。它使用 ICU 正则表达式库,该库已包含在 OSX 中并且是 unicode 安全的。
NSString *str = @"testString";
[str isMatchedByRegex:@"^[a-zA-Z0-9]*$"]; // strict ASCII-match
[str isMatchedByRegex:@"^[\p{L}\p{N}]*$"]; // unicode letters and numbers match
回答by Rob
You can use NSStringregular expression capabilities, introduced in iOS 3.2:
您可以使用NSStringiOS 3.2 中引入的正则表达式功能:
- (BOOL)isAlphanumeric:(NSString *)string {
return [string rangeOfString:@"^[a-zA-Z0-9]+$" options:NSRegularExpressionSearch].location != NSNotFound;
}

