當(dāng)遇到字符串中夾雜網(wǎng)址的時(shí)候,我們一般的方法都是用正則的方式來挑出網(wǎng)址的部分,然后把它替換成文字,這樣就牽涉到正則的運(yùn)用和富文本的使用. 這次我對(duì)正則不再介紹,網(wǎng)上很多這種教程,我這里展示針對(duì)于富文本處理網(wǎng)址的改動(dòng).
以下為大家提供三個(gè)檢測(cè)網(wǎng)絡(luò)的正則表達(dá)式.
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經(jīng)理\r\n\r\n欲知詳情 速速點(diǎ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:@"點(diǎn)擊跳轉(zhuǎn)" 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];
這種情況下就可以替換了.當(dāng)然我們也可以通過NSDataDetector和NSTextCheckingResult進(jìn)行半結(jié)構(gòu)查詢,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)];
至此結(jié)束,有哪里不妥當(dāng)之處,歡迎提出.謝謝