Objective-C - 在字符串中查找URL

Mic*_*ker 14 iphone objective-c nsstring

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

gca*_*amp 44

不需要使用RegexKitLite,因为iOS 4 Apple提供NSDataDetector(子类NSRegularExpression).

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

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

  • 事后看来,在上述评论发表几个月后,它在10.7中被添加到了Mac中. (3认同)

Art*_*pie 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);
Run Code Online (Sandbox Code Playgroud)

打印:

urls: (
    "http://www.google.com",
    "http://www.stackoverflow.com",
    "http://www.apple.com"
)
Run Code Online (Sandbox Code Playgroud)

(当然,我在那里使用的正则表达式是简化的,但你明白了.)