【发布时间】:2012-03-01 21:25:27
【问题描述】:
通过查看NSTextCheckingResult 的文档,我的印象是,如果在NSRegularExpression 搜索中找不到匹配项,则NSCheckingResult 的范围属性将设置为{NSNotFound,0}
从下面的测试中,我发现如果找不到匹配项NSCheckingResult,则范围设置为{0,0}。这是一个小问题,但我只是想澄清一下我对它是如何工作的理解。
// REGEXPRESSION
NSString *textBuffer = @"1234567890";
NSString *pattern = @"(([A-Z]+))";
NSRegularExpression *regExp = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:nil];
NSTextCheckingResult *match = [regExp firstMatchInString:textBuffer options:0 range:NSMakeRange(0, [textBuffer length])];
// ERROR CHECK
if([match range].location == NSNotFound) NSLog(@"Match Not found");
NSLog(@"location: %d", [match range].location);
NSLog(@"length : %d", [match range].length);
// OUTPUT
location: 0
length : 0
编辑:
在此示例中,NSTextCheckingResult *match 被设置为 nil,这可能是位置和长度返回零的原因(向 nil 对象发送消息)。
if(!match) NSLog(@"Match Not Found");
因此,我猜测NSNotFound 仅在有多个捕获组表示空组时才会返回。
【问题讨论】:
-
是的,这是因为空匹配。
{NSNotFound, 0}可以由rangeAtIndex:为未参加比赛的小组返回。 -
@hoha 如果您将评论移到答案中,则模糊山羊可以接受它并将此问题移出未回答队列。
标签: iphone objective-c regex cocoa-touch nsregularexpression