How to extract Image URL using REGEX (NSRegularExpression) in IOS !
Sometimes its very difficult to find image link from an html string. if you have already html strings the us the below sample to extract images
SAMPLE-1
NSRegularExpression* regex = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:&error];
NSArray *matchs = [regex matchesInString:item.summary options:0 range:rangeOfString];
if (matchs.count==0)
{
NSRegularExpression* regex1 = [NSRegularExpression regularExpressionWithPattern:@"(?i)\\b((?:[a-z][\\w-]+:(?:/{1,3}|[a-z0-9%])|www\\d{0,3}[.]|[a-z0-9.\\-]+[.][a-z]{2,4}/)(?:[^\\s()<>]+|\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\))+(?:\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\)|[^\\s`!()\\[\\]{};:'\".,<>?«»“”‘’]))" options:NSRegularExpressionCaseInsensitive error:NULL];
matchs = [regex1 matchesInString:item.summary options:0 range:rangeOfString];
}
for (NSTextCheckingResult* match in matchs)
{
Imagestring=[item.summary substringWithRange:[match rangeAtIndex:1]];
NSString* path =Imagestring;
NSString* extension = [path pathExtension];
if ([extension isEqualToString:@"jpg"])
{
Imagestring=[item.summary substringWithRange:[match rangeAtIndex:1]];
myflag=false;
break;
}
else if ([extension isEqualToString:@"png"])
{
Imagestring=[item.summary substringWithRange:[match rangeAtIndex:1]];
myflag=false;
break;
}
}
SAMPLE-2
NSRange rangeOfString = NSMakeRange(0, [searchedString length]);
//NSLog(@"searchedString: %@", searchedString);
NSString *pattern = @"src=\"([^\"]+)\"";
NSError* error = nil;
NSRegularExpression* regex = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:&error];
NSArray *matchs = [regex matchesInString:searchedString options:0 range:rangeOfString];
for (NSTextCheckingResult* match in matchs) {
NSLog(@"url: %@", [searchedString substringWithRange:[match rangeAtIndex:1]]);
Imagestring=[searchedString substringWithRange:[match rangeAtIndex:1]]
break;
}
SAMPLE-3
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"http?://([-\\w\\.]+)+(:\\d+)?(/([\\w/_\\.]*(\\?\\S+)?)?)?" options:NSRegularExpressionCaseInsensitive error:&error];
NSArray *arrayOfAllMatches = [regex matchesInString:httpLine options:0 range:NSMakeRange(0, [httpLine length])];
NSMutableArray *arrayOfURLs = [[NSMutableArray alloc] init];
for (NSTextCheckingResult *match in arrayOfAllMatches) {
NSString* substringForMatch = [httpLine substringWithRange:match.range];
NSLog(@"Extracted URL: %@",substringForMatch);
[arrayOfURLs addObject:substringForMatch];
}
// return non-mutable version of the array
return [NSArray arrayWithArray:arrayOfURLs];
Discover more from CODE t!ps
Subscribe to get the latest posts sent to your email.