2011-05-14 58 views
13

给定一个大的字符串,创建一个包含在字符串中的所有有效url的数组的最佳方法是什么?Objective-C - 在字符串中查找URL

+0

这是用于显示在一个'UITextView'或'UILabel'或soemthing别的? – dredful 2011-05-14 00:37:59

+0

请参阅[我的答案](http://stackoverflow.com/a/25574255/1966109)了解使用Swift 3的类似问题,并提供了2种方法来解决您的问题。 – 2017-05-08 20:43:46

回答

41

对于此,无需使用RegexKitLite,因为iOS 4 Apple提供NSDataDetectorNSRegularExpression的子类)。

你可以使用它只是像这样(source是你的字符串):

NSDataDetector* detector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeLink error:nil]; 
NSArray* matches = [detector matchesInString:source options:0 range:NSMakeRange(0, [source length])]; 
+0

NSDataDetector *仅适用于iOS *。问题的标题是“* Objective-C *在字符串中查找URL” – 2011-05-14 01:48:39

+0

确实,这取决于Mick在哪个平台上工作......但是看看他最后的问题,他是针对iOS的。 – gcamp 2011-05-14 01:50:51

+3

事后看来,在上述评论几个月后,它被添加到了Mac 10.7。 – Tommy 2013-03-20 01:22:31

6

我会使用RegexKitLite此:

#import "RegExKitLite.h" 

... 

NSString * urlString = @"blah blah blah http://www.google.com blah blah blah http://www.stackoverflow.com blah blah balh http://www.apple.com"; 
NSArray *urls = [urlString componentsMatchedByRegex:@"http://[^\\s]*"]; 
NSLog(@"urls: %@", urls); 

打印:

urls: (
    "http://www.google.com", 
    "http://www.stackoverflow.com", 
    "http://www.apple.com" 
) 

(当然,我用那里的URL正则表达式的简化,但你的想法。 )

-1

这是提取URL链接最好的办法。

NSString *url_ = @"dkc://name.com:8080/123;param?id=123&pass=2#fragment"; 

NSURL *url = [NSURL URLWithString:url_]; 

NSLog(@"scheme: %@", [url scheme]); 

NSLog(@"host: %@", [url host]); 

NSLog(@"port: %@", [url port]); 

NSLog(@"path: %@", [url path]); 

NSLog(@"path components: %@", [url pathComponents]); 

NSLog(@"parameterString: %@", [url parameterString]); 

NSLog(@"query: %@", [url query]); 

NSLog(@"fragment: %@", [url fragment]); 

输出:

方案:DKC

主机:name.com

端口:8080

路径:/ 12345

路径组成部分:( “/”, 123)parameterString:PARAM

查询:ID = 1个&通= 2

片段:片段