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

标签 ios regex cocoa-touch nsstring

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

相关文章:

ios - 将默认状态栏样式设置为 .lightContent,但也允许在某些 View Controller 上进行深色覆盖

ios - 如何使用 Swift 在 LLDB 控制台中使用 _printHierarchy?

php - MySQL REGEXP 仅匹配边界词,但不包括 html 标签中的匹配

ios - 是否可以在 UILabel/TextView 中输入 'hyperlink' 文本,但点击此 'hyperlink' 即可激活 segue?

ios - 以 'new' 前缀开头的属性名称导致 iOS 中的 BAD_ACCESS 错误

ios - 无效的位码版本(生产者 : '800.0.42.1_0' Reader: '703.0.29_0' ) with Xcode 7. 3

ios - "Warning: iPhone apps should include an armv6 architecture"即使设置了构建配置

java从url中剪切文件扩展名

javascript - 替换引号(但不触及嵌套引号)

iphone - 创建的组文件夹在xcode的finder中的显示中不可见