我正在尝试从某些文本中检索图像url字符串,然后创建一个包含所有这些图像url字符串的数组。我想我知道如何使用NSRegularExpression获取图像网址,但我不知道如何获取每个结果。我之前完成了查找和替换,但这只涉及操纵一个巨大的字符串。这是我的代码:
-(NSArray*)parseImages:(NSString*)contents {
NSArray* imageArray = [[NSArray alloc] init];
NSError* error = nil;
NSString* imageHandler = @"\(\?:\\<a\\shref=\"\)https\?:\/\/[\^\/\\s]\+\/\\S\+\\\.\(jpg|png|gif\)";
NSRegularExpression *imageGrabber = [NSRegularExpression regularExpressionWithPattern:imageHandler options:NSRegularExpressionCaseInsensitive error:&error];
if (error)
{
NSLog(@"Couldn't create regex with given string and options");
return nil;
} else {
//Code to add each individual match to imageArray
return imageArray;
}
答案 0 :(得分:2)
这是我在正则表达式中用于多个匹配的内容:
NSArray *matchesArray = [self rangesOfString:@"{regex}" inString:aString];
for (NSValue *rangeVal in matchesArray)
{
NSRange range = [rangeVal rangeValue];
if (range.location != NSNotFound) {
// do stuff with the found range - like add to an NSMutableArray!
}
}
并且rangesOfString方法:
- (NSArray *)rangesOfString:(NSString *)searchString inString:(NSString *)str {
NSMutableArray *results = [NSMutableArray array];
NSRange searchRange = NSMakeRange(0, [str length]);
NSRange range;
while ((range = [str rangeOfString:searchString options:NSRegularExpressionSearch|NSCaseInsensitiveSearch range:searchRange]).location != NSNotFound) {
[results addObject:[NSValue valueWithRange:range]];
searchRange = NSMakeRange(NSMaxRange(range), [str length] - NSMaxRange(range));
}
return results;
}
答案 1 :(得分:1)
让Apple使用NSDataDetector
NSString *text = @"jibberish http://link1.com jibberish http://link2.com jibberish";
NSError *error;
NSDataDetector *dd = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeLink error:&error];
NSArray *matches = [dd matchesInString:text options:0 range:NSMakeRange(0, text.length)];
NSMutableArray *links = [NSMutableArray new];
for (NSTextCheckingResult *result in matches) {
[links addObject:[result URL]];
}
NSLog(@"links: %@", links);
NSLog输出:
链接:(
&#34; http://link1.com&#34 ;,
&#34; http://link2.com&#34;
)
如果需要限制扩展类型:
将扩展添加到集合中:
NSSet *extensions = [NSSet setWithArray: @[@"jpg", @"png", @"gif"]];
仅当扩展名在集合中时才添加到数组中:
NSString *ext = [[url resourceSpecifier] pathExtension];
if ([extensions containsObject:ext]) {
[links addObject:url];
}