日常小知识点

iOS 字符串中判断超链接

2018-06-08  本文已影响3人  _Waiting_
-(NSMutableAttributedString*)subStr:(NSString *)string
{
    NSError *error;
    //可以识别url的正则表达式
    NSString *regulaStr = @"((http[s]{0,1}|ftp)://[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z0-9]{1,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%^&*+?:_/=<>]*)?)";
//    NSString *regulaStr = @"((http[s]{0,1}|ftp)://[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%^&*+?:_/=<>]*)?)|(www.[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%^&*+?:_/=<>]*)?)";
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regulaStr
                                                                           options:NSRegularExpressionCaseInsensitive
                                                                             error:&error];
    NSArray *arrayOfAllMatches = [regex matchesInString:string options:0 range:NSMakeRange(0, [string length])];
    //NSString *subStr;
    NSMutableArray *arr=[[NSMutableArray alloc]init];
    NSMutableArray *rangeArr=[[NSMutableArray alloc]init];
    
    for (NSTextCheckingResult *match in arrayOfAllMatches)
    {
        NSString* substringForMatch;
        substringForMatch = [string substringWithRange:match.range];
        [arr addObject:substringForMatch];
        
    }
    NSSet *set = [NSSet setWithArray:arr];
    arr = [NSMutableArray arrayWithArray:[set allObjects]];
    NSString *subStr=string;
    for (NSString *str in arr)
    {
        [self rangesOfString:str inString:subStr];
        [rangeArr addObject:[self rangesOfString:str inString:subStr]];
        
    }
    
    //计算大小
    UIFont *font = [UIFont systemFontOfSize:15];
    NSMutableAttributedString *attributedText;
    
    attributedText=[[NSMutableAttributedString alloc]initWithString:subStr attributes:@{NSFontAttributeName :font}];
    
    for (NSDictionary *dic in rangeArr)
    {
        NSString *url =  dic[@"url"];
        NSArray *da = dic[@"array"];
        for(NSValue *value in da)
        {
            NSRange range=[value rangeValue];
            [attributedText addAttribute: NSLinkAttributeName value: [NSURL URLWithString:url] range:range];
        }
    }
    
    
    return attributedText;
    
    
}
//获取查找字符串在母串中的NSRange
- (NSDictionary *)rangesOfString:(NSString *)searchString inString:(NSString *)str {
    
    NSMutableArray *results = [NSMutableArray array];
    
    NSRange searchRange = NSMakeRange(0, [str length]);
    
    NSRange range;
    
    while ((range = [str rangeOfString:searchString options:0 range:searchRange]).location != NSNotFound) {
        
        [results addObject:[NSValue valueWithRange:range]];
        
        searchRange = NSMakeRange(NSMaxRange(range), [str length] - NSMaxRange(range));
        
    }
    
    
    NSDictionary *dic = @{@"array":results,@"url":searchString};
    
    return dic;
}
上一篇下一篇

猜你喜欢

热点阅读