在NSArray的第一个索引处为NSString分配字符串

时间:2013-11-29 08:55:07

标签: ios objective-c nsstring nsarray

我正在尝试从名为“newString”的字符串中查找特定的url字符串。我使用以下代码来检测链接并将它们保存在名为“matches”的数组中。我感兴趣的特定字符串位于数组的匹配[1]索引:

NSDataDetector* detector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeLink error:nil];
NSArray* matches = [detector matchesInString:newString options:0 range:NSMakeRange(0, [newString length])];
NSLog(@"MATCHES %@", matches[1]);

如何将匹配[1]中的字符串分配给NSString,以便我可以在我的程序中进一步使用它?

3 个答案:

答案 0 :(得分:0)

NSString *stringYouWant = [matches objectAtIndex:1];

甚至

NSString *stringYouWant = [[matches objectAtIndex:1] copy];

答案 1 :(得分:0)

在您的代码中

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);
    break;
  }
}

其他方式是使用NSRegularExpression

NSRegularExpression *regex = [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:[regex rangeOfFirstMatchInString:someString options:NSMatchingCompleted range:NSMakeRange(0, [someString length])]];
NSLog(@"%@", match);

答案 2 :(得分:0)

这些解决方案中有一个适合您吗? 你尝试过另一场比赛(0,2,3,......)吗? 你也可以尝试另一个索引的范围...

NSDataDetector *detector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeLink error:nil];
NSArray *matches = [detector matchesInString:newString options:0 range:NSMakeRange(0, [newString length])];
NSURL *urlYouWant = [[matches objectAtIndex:1] URL];
NSString *stringYouWant = [newString subStringWithRange:[[matches objectAtIndex:1] rangeAtIndex:1]];