If you replace the part where you loop for the closing double-quote with a call to rangeOfString:options:range:
, passing the range from the end of img src="
substring plus one to the end of the string, your solution would no longer "seem nasty". Of course you could always use regex to look for img src=\"([^\"]*)\"
, but that may need a few extra lines of code:
NSString *str = @"<p><a href=\"/url/10/512.png\"><img src=\"/url/10/512.png\" alt=\" \" border=\"0\" /></a></p><div style=\"clear:both;\"></div>";
NSError *err;
NSRegularExpression *regex = [NSRegularExpression
regularExpressionWithPattern:@"img src=\"([^\"]*)\""
options:NSRegularExpressionCaseInsensitive
error:&err];
NSTextCheckingResult *m = [regex firstMatchInString:str options:0 range:NSMakeRange(0, str.length)];
if (!NSEqualRanges(m.range, NSMakeRange(NSNotFound, 0))) {
NSLog(@"%@", [str substringWithRange:[m rangeAtIndex:1]]);
}
This produces the output of
/url/10/512.png
my string can be longer and consist more than one
img
tag
With the regex above, you can get them all by calling matchesInString:
, and looping over the results.