看来你是对的,但你可以使用一个类别:
#import "NSString+RegEx_Array.h"
@implementation NSString (RegEx_Array)
- (NSArray*)componentsSeparatedByRegex2:(NSString *)pattern
{
NSUInteger pos = 0;
NSRange area = NSMakeRange(0, [self length]);
NSRegularExpression *regEx = [NSRegularExpression
regularExpressionWithPattern:pattern
options:0 error:nil];
NSArray *matchResults = [regEx matchesInString:self options:0 range:area];
NSMutableArray *returnArray = [NSMutableArray arrayWithCapacity:matchResults.count];
for (NSTextCheckingResult *result in matchResults) {
NSRange substrRange = NSMakeRange(pos, [result range].location-pos);
[returnArray addObject:[self substringWithRange:substrRange]];
pos = [result range].location + [result range].length;
}
if (pos < area.length) {
[returnArray addObject:[self substringFromIndex:pos]];
}
return returnArray;
}
@end
但我不得不承认,它的性能不如 RegexKitLite。下面是一个废话文件的输出:
2012-02-08 00:16:32.251 shittyagain[96057:c03] String-Length: 36355200
2012-02-08 00:16:36.420 shittyagain[96057:c03] Time taken RegexKitLite: 4.167
2012-02-08 00:16:42.989 shittyagain[96057:c03] Time taken NSRegularExp: 6.568
和测试代码:
NSString *regx = @"[^a-zA-Z\?]";
NSString *file = [[NSBundle mainBundle]pathForResource:@"reallylong" ofType:nil];
NSString *searchString = [NSString stringWithContentsOfFile:file encoding:NSUTF8StringEncoding error:nil];
NSLog(@"String-Length: %ld", searchString.length);
NSDate *preDate = [NSDate date];
[searchString componentsSeparatedByRegex:regx];
NSLog(@"Time taken RegexKitLite: %1.3f", [preDate timeIntervalSinceNow]*-1);
NSDate *preDate2 = [NSDate date];
[searchString componentsSeparatedByRegex2:regx];
NSLog(@"Time taken NSRegularExp: %1.3f", [preDate2 timeIntervalSinceNow]*-1);
我不确定差异是否真的很重要,因为文件的大小约为 36mb,但以防万一有人需要它真的很快,他必须使用 RegexKitLite。我想如果有人可以发布一些真正的性能测试和/或默认NSRegularExpression
方法。我想知道哪个更快=)