我要完成的工作如下。我有一个 NSString,其中有一个句子,其中有一个 URL。我需要能够获取在 NSString 中的任何句子中显示的 URL,例如:
假设我有这个 NSString
NSString *someString = @"This is a sample of a http://example.com/efg.php?EFAei687e3EsA sentence with a URL within it.";
我需要能够提取http://example.com/efg.php?EFAei687e3EsA从那个 NSString 中。这个 NSString 不是静态的,并且会改变结构,并且 url 不一定在句子的同一位置。我试图研究three20代码,但对我来说毫无意义。这还能怎么做?
最佳答案
使用 NSDataDetector
:
NSString *string = @"This is a sample of a http://example.com/efg.php?EFAei687e3EsA sentence with a URL within it.";
NSDataDetector *linkDetector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeLink error:nil];
NSArray *matches = [linkDetector matchesInString:string options:0 range:NSMakeRange(0, [string length])];
for (NSTextCheckingResult *match in matches) {
if ([match resultType] == NSTextCheckingTypeLink) {
NSURL *url = [match URL];
NSLog(@"found URL: %@", url);
}
}
这样您就不必依赖不可靠的正则表达式,并且随着 Apple 升级他们的链接检测代码,您可以免费获得这些改进。
关于ios - 如何从 NSString 中的句子中提取 URL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4590440/