gpt4 book ai didi

ios - 如何从 NSString 中的句子中提取 URL?

转载 作者:行者123 更新时间:2023-12-03 11:03:09 25 4
gpt4 key购买 nike

我要完成的工作如下。我有一个 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com