假设我有字符串:Objective-C:如何检测字符串中的http URL?
"I love visiting http://www.google.com"
如何检测令牌,http://www.google.com?
假设我有字符串:Objective-C:如何检测字符串中的http URL?
"I love visiting http://www.google.com"
如何检测令牌,http://www.google.com?
您可以使用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);
你能告诉我一个如何使用NSDataDetector? –
为ya添加了一个示例 –
您也可以使用自定义检测器吗?编辑:我看到它只是NSRegulatExpression的一个子类。呵呵,傻了。 – Moshe
你可以这样做:
-(BOOL)textIsUrl:(NSString*)someString {
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES ^[[email protected]:%_\\+.~#?&//=]{2,256}\\.[a-z]{2,4}\\b(\\/[[email protected]:%_\\+.~#?&//=]*)?$"];
[predicate evaluateWithObject:someString];
}
见http://stackoverflow.com/questions/4590440/how-can-i-extract-a-url-from-a-sentence-这是一个nsstring,它提供了几个依赖于目标iOS版本的选项。 – InsertWittyName
可能重复的[无法使用正则表达式检测http链接](http://stackoverflow.com/questions/7002645/unable-to-detect-http-links-using-regex) –