按对象限制NSRegularExpression

时间:2014-02-09 04:50:28

标签: ios objective-c regex nsregularexpression

目前我正在使用NSRegularExpression从rss输出中提取图像。这就是我使用的:

for (NSDictionary *story in stories) {

    NSString *string = [story objectForKey:@"content:encoded"];

    NSRange rangeOfString = NSMakeRange(0, string.length);

    NSString *pattern = @"<img\\s[\\s\\S]*?src\\s*?=\\s*?['\"](.*?)['\"][\\s\\S]*?>";
    NSError* error = nil;

    NSRegularExpression* regex = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:&error];
    NSArray *matchs = [regex matchesInString:[story objectForKey:@"content:encoded"] options:0 range:rangeOfString];
    for (NSTextCheckingResult* match in matchs) {
        NSLog(@"url: %@", [string substringWithRange:[match rangeAtIndex:1]]);
    }


}

这项工作真的很好,除了我只需要每个故事中的一个图像链接,即使是这样的情况(比如这个),每个键有多个图像。

我该如何解决这个问题?

由于

1 个答案:

答案 0 :(得分:0)

听起来你需要做的就是替换你的“matches”循环:

for (NSTextCheckingResult* match in matchs) {
    NSLog(@"url: %@", [string substringWithRange:[match rangeAtIndex:1]]);
}

用这个:

if([matchs count] > 0)
{
    [storyMatches addObject: [string substringWithRange:[match rangeAtIndex:1]]];
}

确保在开始循环stories之前声明storyMatches可变数组:

NSMutableArray *storyMatches = [[NSMutableArray alloc] init];

换句话说,您的代码应如下所示:

NSMutableArray *storyMatches = [[NSMutableArray alloc] initWithCapacity:[stories count]];

for (NSDictionary *story in stories) {

    NSString *string = [story objectForKey:@"content:encoded"];

    NSRange rangeOfString = NSMakeRange(0, string.length);

    NSString *pattern = @"<img\\s[\\s\\S]*?src\\s*?=\\s*?['\"](.*?)['\"][\\s\\S]*?>";
    NSError* error = nil;

    NSRegularExpression* regex = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:&error];
    NSArray *matchs = [regex matchesInString:[story objectForKey:@"content:encoded"] options:0 range:rangeOfString];
    if([matchs count] > 0)
    {
        [storyMatches addObject:[string substringWithRange:[match rangeAtIndex:1]]];
    }
}

NSLog(@"storyMatches count is %d and contents is %@", [storyMatches count], [storyMatches description]);