2012-01-19 62 views
0

现在我的应用程序目标> iOS4我试图删除非Apple框架上的依赖项,尽可能。NSRegularExpression replace RegExkitLite

我有此代码目前

NSString *destination [email protected]"HHH-DDDD>dddd,ffff"; 
    NSString *searchString = destination; 
    NSString *regexString = @"[^a-zA-Z\?]"; 
    NSArray *splitArray = NULL; 
    splitArray = [searchString componentsSeparatedByRegex:regexString]; 

这产生与所有字符的字符串之间元件的阵列。即“HHH”,“DDDD”,“dddd”,“ffff”。

在NSRegularExpression中似乎没有任何等价物,或者我阅读文档错误?

回答

0

看来你是对的,但你可以使用一个类别:

#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方法。我想知道哪一个更快=)