NSDataDetector是NSRegularExpression的子类,主要用于检测半结构化的数据:日期,地址,电话号码,正则表达式等等。
//首先有一段字符串
NSString *str = @"www.baidu.comdhfjdfj17701031767";
//根据检测的类型初始化 这里是检测电话号码和网址
NSDataDetector *detector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypePhoneNumber | NSTextCheckingTypeLink error:&error];
//获得检测所得到的数组
NSArray *matches = [detector matchesInString:str options:0 range:inputRange];
//获得检测得到的总数
//- (NSUInteger)numberOfMatchesInString:(NSString *)string options:(NSMatchingOptions)options range:(NSRange)range;
//第一个检测到的数据
//- (NSTextCheckingResult *)firstMatchInString:(NSString *)string options:(NSMatchingOptions)options range:(NSRange)range;
for(NSTextCheckingResult*match in matches) {
//当match匹配为网址时设置颜色
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:str];
if ([match resultType] == NSTextCheckingTypeLink) {
NSRange matchRange = [match range]; //这里可以自行设置
[attributedStringaddAttribute:NSForegroundColorAttributeName value:[UIColor yellowColor] range:matchRange];
[attributedStringaddAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:matchRange];
}
//当match匹配为电话号码时设置其attribute
if ([match resultType] == NSTextCheckingTypePhoneNumber) {
NSRange matchRange = [match range];
//这里可以自行设置
[attributedStringaddAttribute:NSForegroundColorAttributeName value:[UIColor yellowColor] range:matchRange];
[attributedStringaddAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:matchRange];
}
}
//设置label的内容
//textLabel.attributedText = attributedString;