NSRegularExpression 给出了 numberOfRanges 方法的错误结果

NSRegularExpression is giving incorrect result from the numberOfRanges method

我的代码很小

创建一个新的 XCode 项目并将此代码粘贴到 运行:

NSString *stringToCheck = @"## master...origin/master [ahead 1, behind 1]";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\[(ahead) (\d), (behind) (\d)\]|\[(behind) (\d)\]|\[(ahead) (\d)\]" options:0 error:nil];

NSArray* matches = [regex matchesInString:stringToCheck options:0 range:NSMakeRange(0, [stringToCheck length])];
NSTextCheckingResult *match = [matches firstObject];
NSUInteger numberOfRanges = [match numberOfRanges];

numberOfRanges 我得到 = 9。但这不应该是 5 吗?

编辑:更多信息 数据可以有 3 种形式

1. ## master...origin/master [ahead 1, behind 1]
2. ## master...origin/master [ahead 1]
3. ## master...origin/master [behind 1]

我如何编写代码来说明所有 3 种情况?在不知道找到哪个匹配项的情况下,我不知道如何进行。根据下面的一个答案,似乎 [match numberOfRanges] 将 return 完整匹配计数,无论是否找到。

如果数据恰好是#1,则[match rangeOfIndex:0-4]方法有效。其他索引失败。

如果数据恰好是#2,则[match rangeOfIndex:5-6]方法有效。其他失败

如果数据恰好是#3,则[match rangeOfIndex:7-8]方法有效。其他人失败了。

那么我如何知道捕获了哪个组,这样我就知道要搜索哪个范围?

编辑:根据给定的回复回答

    if ([match rangeAtIndex:1].location != NSNotFound) { // The First capture group
        aheadCount = [stringToCheck substringWithRange:[match rangeAtIndex:2]];
        behindCount = [stringToCheck substringWithRange:[match rangeAtIndex:4]];
    } else if ([match rangeAtIndex:5].location != NSNotFound) { //The second Capture group
        aheadCount = [stringToCheck substringWithRange:[match rangeAtIndex:6]];
    } else if ([match rangeAtIndex:7].location != NSNotFound) { //The third capture group
        behindCount = [stringToCheck substringWithRange:[match rangeAtIndex:8]];
    }

模式中的每个组 (...) 都会产生一个匹配范围,整个模式(索引为 0)也是如此 - 总共有 9 个。使用 or,|, 不会改变这一点,因此编号保持一致 - 每个组都有一个唯一的编号。

在您的示例中,如果您检查所有范围,您会发现对于匹配项 5 到 8,NSRange location 值为 NSNotFound,因为您的字符串匹配包含的第一个替代项第 1 组到第 4 组。

注意:由于每个组都有一个唯一的编号,通过测试 NSNotFound,您可以确定匹配的备选方案。