Objective-C - Finding a URL within a string

て烟熏妆下的殇ゞ 提交于 2019-11-27 12:25:53

问题


Given a large string, what is the best way to create an array of all valid urls which are contained within the string?


回答1:


No need to use RegexKitLite for this, since iOS 4 Apple provide NSDataDetector (a subclass of NSRegularExpression).

You can use it simply like this (source is your string) :

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



回答2:


I'd use RegexKitLite for this:

#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);

Prints:

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

(Of course, the regex I've used there for urls is simplified, but you get the idea.)




回答3:


This is best way to extract url link.

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]);

Output:

scheme: dkc

host: name.com

port: 8080

path: /12345

path components: ( "/", 123 ) parameterString: param

query: id=1&pass=2

fragment: fragment



来源:https://stackoverflow.com/questions/5998969/objective-c-finding-a-url-within-a-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!