URLs
我有一个需要从给定中提取的场景NSStrings
,所以我找到了两种方法来做到这一点(在 SO 的帮助下 :))......
这样我就有一个NSString
这样的
NSString *someString = @"This is a sample of a http:\/\/www.abc.com\/efg.php?EFAei687e3EsA sentence with a URL within it.";
然后我可以使用这两种方法来摆脱URL
字符串...
第一种方式
NSRegularExpression *expression = [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];
NSString *match = [someString substringWithRange:[expression rangeOfFirstMatchInString:someString options:NSMatchingCompleted range:NSMakeRange(0, [someString length])]];
NSLog(@"%@", match);
第二种方式
NSDataDetector *linkDetector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeLink error:nil];
NSArray *matches = [linkDetector matchesInString:someString options:0 range:NSMakeRange(0, [someString length])];
for (NSTextCheckingResult *match in matches) {
if ([match resultType] == NSTextCheckingTypeLink) {
NSURL *url = [match URL];
NSLog(@"found URL: %@", url);
}
}
我的问题是哪一个更好更快,因为我有大约400 到 500NSStrings
个实例要解析。
先感谢您。