How can I extract a URL from a sentence that is in a NSString? How can I extract a URL from a sentence that is in a NSString? ios ios

How can I extract a URL from a sentence that is in a NSString?


Use an NSDataDetector:

NSString *string = @"This is a sample of a http://example.com/efg.php?EFAei687e3EsA sentence with a URL within it.";NSDataDetector *linkDetector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeLink error:nil];NSArray *matches = [linkDetector matchesInString:string options:0 range:NSMakeRange(0, [string length])];for (NSTextCheckingResult *match in matches) {  if ([match resultType] == NSTextCheckingTypeLink) {    NSURL *url = [match URL];    NSLog(@"found URL: %@", url);  }}

This way you don't have to rely on an unreliable regular expression, and as Apple upgrades their link detection code, you get those improvements for free.


Edit: I'm going to go out on a limb here and say you should probably use NSDataDetector as Dave mentions. Far less prone to error than regular expressions.


Take a look at regular expressions. You can construct a simple one to extract the URL using the NSRegularExpression class, or find one online that you can use. For a tutorial on using the class, see here.


The code you want essentially looks like this (using John Gruber's super URL regex):

NSRegularExpression *expression = [NSRegularExpression regularExpressionWithPattern:@"(?i)\\b((?:[a-z][\\w-]+:(?:/{1,3}|[a-z0-9%])|www\\d{0,3}[.]|[a-z0-9.\\-]+[.][a-z]{2,4}/)(?:[^\\s()<>]+|\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\))+(?:\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\)|[^\\s`!()\\[\\]{};:'\".,<>?«»“”‘’]))" options:NSRegularExpressionCaseInsensitive error:NULL];NSString *someString = @"This is a sample of a http://example.com/efg.php?EFAei687e3EsA sentence with a URL within it.";NSString *match = [someString substringWithRange:[expression rangeOfFirstMatchInString:someString options:NSMatchingCompleted range:NSMakeRange(0, [someString length])]];NSLog(@"%@", match); // Correctly prints 'http://example.com/efg.php?EFAei687e3EsA'

That will extract the first URL in any string (of course, this does no error checking, so if the string really doesn't contain any URL's it won't work, but take a look at the NSRegularExpression class to see how to get around it.


Use Like This:

NSError *error = nil;NSDataDetector *detector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeLink                                                           error:&error];[detector enumerateMatchesInString:someString                           options:0                             range:NSMakeRange(0, someString.length)                        usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {     if (result.resultType == NSTextCheckingTypeLink)     {         NSString *str = [NSString stringWithFormat:@"%@",result.URL];         NSLOG(%@,str);     } }];

This will Output the all links in your someString one by one


matomo