2011-08-10 26 views
7

假设我有字符串:Objective-C:如何检测字符串中的http URL?

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

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

+0

见http://stackoverflow.com/questions/4590440/how-can-i-extract-a-url-from-a-sentence-这是一个nsstring,它提供了几个依赖于目标iOS版本的选项。 – InsertWittyName

+0

可能重复的[无法使用正则表达式检测http链接](http://stackoverflow.com/questions/7002645/unable-to-detect-http-links-using-regex) –

回答

24

您可以使用NSDataDetectors这些都是在iOS4中添加的,非常有用。你想用​​创建一个数据检测器,并让它做到这一点。

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); 
+0

你能告诉我一个如何使用NSDataDetector? –

+0

为ya添加了一个示例 –

+0

您也可以使用自定义检测器吗?编辑:我看到它只是NSRegulatExpression的一个子类。呵呵,傻了。 – Moshe

1

你可以这样做:

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

    [predicate evaluateWithObject:someString]; 
}