本文原文地址 http://www.cnblogs.com/qianLL/p/6082287.html
有时候 后台返回的是一串html'字符串 我们需要把里面的图片地址提取出来 这个关键就是一个正确的正则表达式
即
<(img|IMG)(.*?)(/>|></img>|>)
具体代码如下 返回的是这串字符串里面所有的图片地址 所有是一个集合
+ (NSArray *)filterImage:(NSString *)html
{
NSMutableArray *resultArray = [NSMutableArray array]; NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"<(img|IMG)(.*?)(/>|></img>|>)" options:NSRegularExpressionAllowCommentsAndWhitespace error:nil];
NSArray *result = [regex matchesInString:html options:NSMatchingReportCompletion range:NSMakeRange(, html.length)]; for (NSTextCheckingResult *item in result) {
NSString *imgHtml = [html substringWithRange:[item rangeAtIndex:]]; NSArray *tmpArray = nil;
if ([imgHtml rangeOfString:@"src=\""].location != NSNotFound) {
tmpArray = [imgHtml componentsSeparatedByString:@"src=\""];
} else if ([imgHtml rangeOfString:@"src="].location != NSNotFound) {
tmpArray = [imgHtml componentsSeparatedByString:@"src="];
} if (tmpArray.count >= ) {
NSString *src = tmpArray[]; NSUInteger loc = [src rangeOfString:@"\""].location;
if (loc != NSNotFound) {
src = [src substringToIndex:loc];
[resultArray addObject:src];
}
}
} return resultArray;
}