Objective-C:如何在字符串中检测http URL?

时间:2011-08-10 16:11:31

标签: iphone objective-c regex cocoa-touch nsstring

我们假设我有字符串:

"I love visiting http://www.google.com"

如何检测令牌http://www.google.com

2 个答案:

答案 0 :(得分:26)

你可以使用NSDataDetectors这些是在iOS4中添加的,非常有用。您想要使用NSTextCheckingTypeLink创建一个数据检测器,让它做它的事情。

NSString *testString = @"Hello http://google.com world";
NSDataDetector *detect = [[NSDataDetector alloc] initWithTypes:NSTextCheckingTypeLink error:nil];
NSArray *matches = [detect matchesInString:testString options:0 range:NSMakeRange(0, [testString length])];
NSLog(@"%@", matches);

答案 1 :(得分:1)

您可以执行以下操作:

-(BOOL)textIsUrl:(NSString*)someString {
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES ^[-a-zA-Z0-9@:%_\\+.~#?&//=]{2,256}\\.[a-z]{2,4}\\b(\\/[-a-zA-Z0-9@:%_\\+.~#?&//=]*)?$"];

    [predicate evaluateWithObject:someString];
}