当遇到字符串中夹杂网址的时候,我们一般的方法都是用正则的方式来挑出网址的部分,然后把它替换成文字,这样就牵涉到正则的运用和富文本的使用. 这次我对正则不再介绍,网上很多这种教程,我这里展示针对于富文本处理网址的改动.
以下为大家提供三个检测网络的正则表达式.
NSString *str = @"http(s)?:\\/\\/([\\w-]+\\.)+[\\w-]+(\\/[\\w- .\\/?%&=]*)?";
NSString *str=@"((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\\.\\-~!@;#$%^&*+?:_/=<>]*)?)";
NSString *str = @"\\bhttps?://[a-zA-Z0-9\\-.]+(?::(\\d+))?(?:(?:/[a-zA-Z0-9\\-._?,'+\\&%$=~*!():@\\\\]*)+)?";
接下来我们就具体说富文本的替换,我以文本输入视图来举例.
NSString *textStr = @"PayPaldsfasdfasdfasd\r\n\r\nasdfasdfasdfasdfasdf\r\n\r\nasdf dfasdfasdf经理\r\n\r\n欲知详情 速速点开\r\nhttp:\/\/mp.weixin.qq.com\/s?__biz=MzA4ODA0OTMwMg==&mid=2652008899&idx=1&sn=b20c06a4f57c30fb006bd7ccffa47f49&scene=1&srcid=0621bBzGgLMpPUVtbEN5U6hM&pass_ticket=mPUl1U6o9bwqVulHDmxhAZTNaS6TJydHZEsAL63HW5gEG03F8bSYZa8nkLdtbeYq
UITextView *textView = [[UITextView alloc]initWithFrame:self.view.frame];
textView.text = textStr;
NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc]initWithString:textStr];
NSString *str = @"\\bhttps?://[a-zA-Z0-9\\-.]+(?::(\\d+))?(?:(?:/[a-zA-Z0-9\\-._?,'+\\&%$=~*!():@\\\\]*)+)?";
NSError *error;
NSRegularExpression *expression = [NSRegularExpression regularExpressionWithPattern:str options:NSRegularExpressionCaseInsensitive error:&error];
NSArray *resultArray = [expression matchesInString:textView.attributedText.string options:0 range:NSMakeRange(0, textView.attributedText.string.length)];
for (NSTextCheckingResult * match in resultArray) {
NSString * subStringForMatch = [textView.attributedText.string substringWithRange:match.range];
NSMutableDictionary * dict = [NSMutableDictionary dictionary];
dict[NSFontAttributeName] = [UIFont systemFontOfSize:14.0];
dict[NSForegroundColorAttributeName] = [UIColor blueColor];
NSMutableAttributedString * temStr = [[NSMutableAttributedString alloc]initWithString:@"点击跳转" attributes:dict];
[temStr addAttribute:NSLinkAttributeName value:[NSURL URLWithString:subStringForMatch] range:NSMakeRange(0, temStr.length)];
[attrStr replaceCharactersInRange:match.range withAttributedString:temStr];
textView.attributedText = attrStr;
}
[self.view addSubview:textView];
这种情况下就可以替换了.当然我们也可以通过NSDataDetector和NSTextCheckingResult进行半结构查询,NSDataDetector是NSRegularExpression的子类可将以下代码替换上面的判断部分;
NSDataDetector *dataDetector=[NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeLink error:&error];
NSArray *arrayOfAllMatches=[dataDetector matchesInString:textView.attributedText.string options:NSMatchingReportProgress range:NSMakeRange(0, textView.attributedText.string.length)];
至此结束,有哪里不妥当之处,欢迎提出.谢谢