Iphone Objective-C-在字符串中查找URL
给定一个大字符串,创建包含在该字符串中的所有有效URL的数组的最佳方法是什么?我将使用以下方法:Iphone Objective-C-在字符串中查找URL,iphone,objective-c,nsstring,Iphone,Objective C,Nsstring,给定一个大字符串,创建包含在该字符串中的所有有效URL的数组的最佳方法是什么?我将使用以下方法: #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
#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的正则表达式被简化了,但你明白了。)无需使用
RegexKitLite
,因为iOS 4 Apple提供了NSDataDetector
(NSRegularExpression的子类)
您可以这样简单地使用它(source
是您的字符串):
这是提取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)参数字符串:param
查询:id=1和pass=2
片段:片段
这是用于在
UITextView
或UILabel
中显示还是用于其他内容?有关使用Swift 3并给出2种解决问题方法的类似问题,请参阅。NSDataDetector仅在iOS上可用。问题的标题是“Objective-C在字符串中查找URL”是的,这取决于Mick使用的平台。。。但看看他最后的问题,他是针对iOS的。事后来看,在上面的评论发表几个月后,它在10.7版本中被添加到Mac中。对我来说,它在最后增加了一个额外的引用
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]);