【问题标题】:NSRegularExpression is giving incorrect result from the numberOfRanges methodNSRegularExpression 从 numberOfRanges 方法给出了不正确的结果
【发布时间】:2015-10-31 17:15:06
【问题描述】:

我的代码很小

创建一个新的 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] 似乎将返回完整的匹配计数,无论是否找到。

如果数据恰好是#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]];
    }

【问题讨论】:

    标签: objective-c regex cocoa cocoa-touch nsregularexpression


    【解决方案1】:

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

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

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

    【讨论】:

    • 我如何检查哪个组 = NSNotFound?我尝试了这样的 while 循环,但没有用 -> while ((aRange = [match rangeAtIndex:index++]) == NSNotFound)
    • NSRangelocation 值是NSNotFound,所以你需要像aRange.location == NSNotFound 这样的东西
    猜你喜欢
    • 2022-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-13
    • 2012-08-27
    • 2017-12-14
    • 2019-03-12
    • 1970-01-01
    相关资源
    最近更新 更多