0

现在我的应用程序目标 >iOS4 我正在尝试尽可能删除对非 Apple 框架的依赖。

我目前有这个代码

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

这会在所有字符之间生成一个包含字符串元素的数组。即“HHH”、“DDDD”、“dddd”、“ffff”。

NSRegularExpression 中似乎根本没有等价物,还是我读错了文档?

4

1 回答 1

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

于 2012-02-07T23:28:25.460 回答