NSRegularExpression匹配错误

时间:2013-10-30 07:27:59

标签: ios objective-c nsregularexpression

我使用NSRegularExpression解压缩字符串。将@“A”转移到@“, - 1”并将@“B”转移到@“, - 2”将其解压缩。

问题是如果仅单独应用@"A" to @",-1" or @"B" to @",-2",它可以正常工作。但是当在for循环中应用两者时,我发现enumerateMatchesInString:options:range:usingBlock在搜索@"B"时找不到匹配项。 有什么想法吗?

NSString *compressed = @"[303b18c01a,Ac24a6,Aa6,,Ah,A,a1,,,a8,b,c5,aad,bcg,dha9,fa4a7,ib4a9,da4a5,ca1a6,aha7,aea6,,aa6,BCa8,]";
NSMutableString *compressedCopy = [compressed mutableCopy];

//the array contains two patterns
NSArray *regulars = @[[self regexO:@"A" n:@",-1"],
                      [self regexO:@"B" n:@",-2"]];

NSInteger count = [regulars count];
    for (int i = 0; i < count; i++) {

        NSDictionary *regexInfo = regulars[i];
        NSString *old = regexInfo[REGEX_OLD_KEY];
        NSString *new = regexInfo[REGEX_NEW_KEY];

        NSString *origin = [compressedCopy copy];

        NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:old options:0 error:nil];

        if (regex) {
            __block int offset = 0;
            [regex enumerateMatchesInString:origin options:0 range:NSMakeRange(0, [compressed length]) usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {

                NSRange range = [result range];
                range.location += offset;
                [compressedCopy replaceCharactersInRange:range withString:new];
                offset += [new length] - [old length];
            }];
    }

接下来是保存模式

- (NSDictionary *)regexO:(NSString *)old n:(NSString *)new
{
    NSDictionary *regex = @{REGEX_OLD_KEY: old, REGEX_NEW_KEY: new};
    return regex;
}

--------------------------让它更清晰---------------- ---------

原始数据是包含许多点坐标的数组,例如:

[131,61,648,1,1,-1,0]

我需要处理的压缩数据就像 - &gt; NSString *压缩。

解压缩算法是改变压缩字符串中的字符,例如将“A”改为@“, - 1”。

1 个答案:

答案 0 :(得分:0)

终于发现这是一个愚蠢的错误。传递给方法的范围是错误的,因此无法生成正确的结果。

[regex enumerateMatchesInString:origin options:0 range:NSMakeRange(0, [origin length]) usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop)