【发布时间】: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