我使用NSRegularExpression从HTML中提取图像URL。但是,当尝试实际使用它时,我会得到以下错误:
由于“NSInvalidArgumentException”异常而终止应用程序,原因:“* enumerateMatchesInString:options:range:usingBlock::-NSRegularExpression -NSRegularExpression 0参数”
我看过像这这样的其他堆栈溢出的答案,但是这个问题使用的是NSMatchingOption,而我不使用,并且这个答案没有给出关于我的情况有什么问题的信息。
下面是正在崩溃的代码:
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"(<img\\s[\\s\\S]*?src\\s*?=\\s*?['\"](.*?)['\"][\\s\\S]*?>)+?" options:NSRegularExpressionCaseInsensitive error:nil];
NSString *source = [NSString stringWithContentsOfURL:[NSURL URLWithString:object[@"link"]] encoding:NSUTF8StringEncoding error:nil];
NSArray *imageResults = [regex matchesInString:source options:0 range:NSMakeRange(0, source.length)];
NSURL *link = [imageResults.firstObject URL];
UIImage *img = [UIImage imageWithData:[NSData dataWithContentsOfURL:link]];
if (img)
{
[self.images setObject:img forKey:object[@"link"]];
dispatch_async(dispatch_get_main_queue(), ^{
cell.imageView.image = img;
[cell layoutSubviews];
});
}崩溃本身发生在实例化imageResults的行上。
有人知道这个代码有什么问题吗?
发布于 2014-10-03 02:58:38
有一个问题:matchesInString:source返回一个NSTextCheckingResults数组。
例如,必须添加错误检查:
NSString *regExp = @"<img\\s+src=[\"']([^\"']+)";
NSError *error;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regExp options:NSRegularExpressionCaseInsensitive error:&error];
NSString *source = @"leading<img src=\"news.google.com/news/…\" alt=\"Smiley face\">more";
NSArray *matchResults = [regex matchesInString:source options:0 range:NSMakeRange(0, source.length)];
NSTextCheckingResult *result0 = matchResults[0];
NSRange imgRange = [result0 rangeAtIndex:1];
NSLog(@"imgRange: %@, '%@'", NSStringFromRange(imgRange), [source substringWithRange:imgRange]);输出:
imgRange:{17,22},'news.google.com/news/…‘
见: ICU用户指南正则表达式
https://stackoverflow.com/questions/26172184
复制相似问题