0

我有一个像这样的字符串:

"This is test string http://www.google.com and it is working."

我只想http://www.google.com从上面的字符串中获取链接()。我怎么才能得到它?

4

3 回答 3

1

它应该像这样工作:

NSString *test = @"This is test string http://www.google.com and it is working.";

NSString *string = [test stringByAppendingString:@" "];

NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"https?://[^ ]* "
                                                                       options:0
                                                                         error:&error];
NSArray *matches = [regex matchesInString:string
                                  options:0
                                    range:NSMakeRange(0, [string length])];

for (NSTextCheckingResult *match in matches) {
    NSRange matchRange = [match range];
    NSString *url = [string substringWithRange:matchRange];

    NSLog(@"Found URL: %@", url);
}

您可以在此处找到有关使用 NSRegularExpression 的更多信息:

https://developer.apple.com/library/mac/#documentation/Foundation/Reference/NSRegularExpression_Class/Reference/Reference.html

于 2012-08-14T07:32:46.987 回答
0

查看 NSString 类文档 - 那里有很多方法可以找到某些子字符串格式的位置、在分隔符上拆分字符串以及提取子字符串等。

例如,在上面的示例中,如果您想提取字符串中的任何嵌入式 url,您可以首先使用以下方法拆分字符串:

NSArray *substrings = [myString componentsSeparatedByString:@" "];

然后在结果数组中,遍历它并找出它是否有一个'http'字符串:

for (int i=0;i<[substrings length];i++) {
   NSString aStr = [substrings objectAtIndex:i];
   if ([aStr rangeOfString:@"http"].location != NSNotFound) {
        NSLog(@"I found a http url:%@", aStr);
   }
}
于 2012-08-14T07:32:52.177 回答
0

这将像一个 CHARM 一样工作:

NSString *totalString = @"This is test string http://www.google.com and it is working.";
NSLog(@"%@", totalString);

NSRange urlStart = [totalString rangeOfString: @"http"];
NSRange urlEnd = [totalString rangeOfString: @".com"];
NSRange resultedMatch = NSMakeRange(urlStart.location, urlEnd.location - urlStart.location + urlEnd.length);

NSString *linkString = [totalString substringWithRange:resultedMatch];

NSLog (@"%@", linkString);
于 2012-08-14T07:36:08.880 回答