我目前正在使用NSDataDetectors查找链接:
-(void)setBodyText
{
NSString* labelText = [[message valueForKey:@"body"]gtm_stringByUnescapingFromHTML];
NSDataDetector *linkDetector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeLink error:nil];
NSArray *matches = [linkDetector matchesInString:labelText options:0 range:NSMakeRange(0, [labelText length])];
for (NSTextCheckingResult *match in matches) {
if ([match resultType] == NSTextCheckingTypeLink) {
NSURL *url = [match URL];
[bodyLabel addCustomLink:url inRange:[match range]];
NSLog(@"found URL: %@", url);
}
}
[bodyLabel setText:labelText];
[Utils alignLabelWithTop:bodyLabel];
}
如何使用NSDataDetectors解析@,例如:
"Hello @sheehan, you are cool"
我希望它能够检测到@sheehan
注意:我想使用NSDataDetector或正则表达式模式匹配。没有客户标签或控件等。
答案 0 :(得分:4)
您可以使用此方法使用NSRegularExpression查找@name匹配。
- (NSMutableArray *)findTwitterHandle:(NSString *)text {
NSError *error = nil;
NSRegularExpression *regex = [[NSRegularExpression alloc] initWithPattern:@"(@[a-zA-Z0-9_]+)"
options:NSRegularExpressionCaseInsensitive
error:&error];
if (error != nil) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error"
message:[error localizedDescription]
delegate:nil
cancelButtonTitle:nil
otherButtonTitles:@"Ok", nil];
[alert show];
[alert release];
}
NSMutableArray *siteNames = [NSMutableArray array];
NSArray *matches = [regex matchesInString:text options:0 range:NSMakeRange(0, [text length])];
for (NSTextCheckingResult *result in matches) {
[siteNames addObject:[text substringWithRange:result.range]];
}
[regex release];
return siteNames;
}
此方法将返回带有所有匹配字符串的NSMutableArray。