Mick Walker
Mick Walker

Reputation: 3847

Objective-C - Finding a URL within a string

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

Upvotes: 14

Views: 9936

Answers (3)

DURGESH
DURGESH

Reputation: 2453

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

Upvotes: -1

gcamp
gcamp

Reputation: 14662

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

Upvotes: 49

Art Gillespie
Art Gillespie

Reputation: 8757

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.)

Upvotes: 6

Related Questions