我正在尝试提出一种算法来在文本正文中查找 URL。我目前有以下代码(这是我坐下来破解的代码,我知道必须有更好的方法):
statusText.text = @"http://google.com http://www.apple.com www.joshholat.com";
NSMutableArray *urlLocations = [[NSMutableArray alloc] init];
NSRange currentLocation = NSMakeRange(0, statusText.text.length);
for (int x = 0; x < statusText.text.length; x++) {
currentLocation = [[statusText.text substringFromIndex:(x + currentLocation.location)] rangeOfString:@"http://"];
if (currentLocation.location > statusText.text.length) break;
[urlLocations addObject:[NSNumber numberWithInt:(currentLocation.location + x)]];
}
currentLocation = NSMakeRange(0, statusText.text.length);
for (int x = 0; x < statusText.text.length; x++) {
currentLocation = [[statusText.text substringFromIndex:(x + currentLocation.location)] rangeOfString:@"http://www."];
if (currentLocation.location > statusText.text.length) break;
[urlLocations addObject:[NSNumber numberWithInt:(currentLocation.location + x)]];
}
currentLocation = NSMakeRange(0, statusText.text.length);
for (int x = 0; x < statusText.text.length; x++) {
currentLocation = [[statusText.text substringFromIndex:(x + currentLocation.location)] rangeOfString:@" www." options:NSLiteralSearch];
if (currentLocation.location > statusText.text.length) break;
[urlLocations addObject:[NSNumber numberWithInt:(currentLocation.location + 1 + x)]];
}
//Get rid of any duplicate locations
NSSet *uniqueElements = [NSSet setWithArray:urlLocations];
[urlLocations release];
NSArray *finalURLLocations = [[NSArray alloc] init];
finalURLLocations = [uniqueElements allObjects];
//Parse out the URLs of each of the locations
for (int x = 0; x < [finalURLLocations count]; x++) {
NSRange temp = [[statusText.text substringFromIndex:[[finalURLLocations objectAtIndex:x] intValue]] rangeOfString:@" "];
int length = temp.location + [[finalURLLocations objectAtIndex:x] intValue];
if (temp.location > statusText.text.length) length = statusText.text.length;
length = length - [[finalURLLocations objectAtIndex:x] intValue];
NSLog(@"URL: %@", [statusText.text substringWithRange:NSMakeRange([[finalURLLocations objectAtIndex:x] intValue], length)]);
}
我觉得它可以通过使用正则表达式或其他东西来改进。非常感谢任何有助于改进这一点的帮助。
最佳答案
如果您的目标是 iOS 4.0+,您应该让 Apple 为您完成工作并使用内置的数据检测器。使用 NSTextCheckingTypeLink
选项创建 NSDataDetector
实例,并在您的字符串上运行它。 documentation for NSDataDetector有一些关于类用法的很好的例子。
如果您出于任何原因不/不能使用数据检测器,几个月前 John Gruber 发布了一个用于检测 URL 的良好正则表达式模式:http://daringfireball.net/2010/07/improved_regex_for_matching_urls
关于objective-c - 改进在文本正文中查找 URL 的算法 - obj-c,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4556286/