NSRegularExpression is giving incorrect result from the numberOfRanges method

泄露秘密 提交于 2019-12-11 11:30:26

问题


My code is small

Create a new XCode project and past this code to run:

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];

The numberOfRanges im getting = 9. But should'nt this be 5 ?

EDIT: More information the data can come in 3 forms

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

How do i write code to account for all 3 scenarios? Without knowing which match was found, I do not know how to proceed. Based on one answer below it seems that [match numberOfRanges] will return the full match count whether or not its found.

If the data happens to be #1, then the [match rangeOfIndex:0-4] method works. Other Indexes fail.

If the data happens to be #2, then the [match rangeOfIndex:5-6] method works. Others fail

If the data happens to be #3, then the [match rangeOfIndex:7-8] method works. Others fail.

So how do i tell which group was captured, so i know which range to search?

EDIT: Answer based on the response given

    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]];
    }

回答1:


Every group, (...), in your pattern will produce a matching range, as will the whole pattern (with index 0) - giving you a total of 9. The use of or, |, does not change this so numbering remains consistent - every group has a unique number.

In your example if you examine all the ranges you will find that for matches 5 through 8 the NSRange location value is NSNotFound as your string matches the first alternative which contains groups 1 through 4.

Note: As each group has a unique number by testing for NSNotFound you can determine which alternative has been matched.



来源:https://stackoverflow.com/questions/31891627/nsregularexpression-is-giving-incorrect-result-from-the-numberofranges-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!