需求:匹配文本內容中的標籤,而後高亮顯示出來。html
運行環境:XCode8.1, iPhone7-iOS10.1
第三方類庫框架:ios
Undefined symbols for architecture x86_64: "_u_errorName", referenced from: _rkl_NSExceptionForRegex in RegexKitLite.o _rkl_makeNSError in RegexKitLite.o _rkl_userInfoDictionary in RegexKitLite.o _rkl_NSExceptionForRegex in MOBFoundation _rkl_userInfoDictionary in MOBFoundation "_u_strlen", referenced from: _rkl_userInfoDictionary in RegexKitLite.o _rkl_userInfoDictionary in MOBFoundation "_uregex_appendReplacement", referenced from: _rkl_replaceAll in RegexKitLite.o _rkl_replaceAll in MOBFoundation "_uregex_appendTail", referenced from: _rkl_replaceAll in RegexKitLite.o _rkl_replaceAll in MOBFoundation 省略...
感謝 使用Xcode開發,錯誤總結<持續更新ing>正則表達式
#import "ViewController.h" #import "YYText.h" #import "RegexKitLite.h" #define kScreenWidth [UIScreen mainScreen].bounds.size.width @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; YYLabel *label = [[YYLabel alloc] initWithFrame:CGRectMake(0, 100, kScreenWidth, 16)]; label.text = @"佔位符佔位符<a href='https://www.xxx.com/223?232323&2323'>#我是連接1#</a>佔位符<a href='https://www.xxx.com/223?232323&2323'>#我是連接2#</a>佔佔位符佔位符佔位符佔位符佔位符佔位符佔位符佔位符佔位符佔位符"; // url正則有不少種,不過這個已經夠知足個人需求 NSString *regex_http = @"<a href=(?:.*?)>(.*?)<\\/a>"; // 文本內容 NSString *labelText = [label.text copy]; //[label.text captureComponentsMatchedByRegex:@""]; // 只會匹配第一個知足條件的 // 這個方法能夠匹配多個知足條件的,獲得一個二維數組。內容中可能會有多個連接,因此要用這個 NSArray *array_http = [labelText arrayOfCaptureComponentsMatchedByRegex:regex_http]; if ([array_http count]) { // 先把html a標籤都給去掉 labelText = [labelText stringByReplacingOccurrencesOfString:@"<a href=(.*?)>" withString:@"" options:NSRegularExpressionSearch range:NSMakeRange (0, labelText.length)]; labelText = [labelText stringByReplacingOccurrencesOfString:@"<\\/a>" withString:@"" options:NSRegularExpressionSearch range:NSMakeRange (0, labelText.length)]; // 樣式文本 NSMutableAttributedString *one = [[NSMutableAttributedString alloc] initWithString: labelText]; // 處理掉a標籤後的內容,用來讓UILabel去顯示 label.text = labelText; for (NSArray *array in array_http) { // 得到連接顯示文字的range,用來設置下劃線 NSRange range = [labelText rangeOfString:array[1]]; // 設置下劃線樣式 [one yy_setTextUnderline:[YYTextDecoration decorationWithStyle:YYTextLineStyleSingle] range:range]; // 設置連接文本字體顏色 UIColor *textColor = [UIColor redColor]; [one yy_setColor:textColor range:range]; } // 設置UILabel樣式 label.attributedText = one; } [self.view addSubview:label]; } @end
<a href=(?:.*?)>
, 這個正則這裏要主要貪婪匹配的問題。若是是<a href=(?:.*)>
那個會匹配到:數組
一直匹配到最後一個a標籤,就得不到每一個連接了。app
YYText也能夠實現高亮a連接文本的點擊事件。具體能夠參考下邊的第二篇博客框架
感謝:1. iOS中使用RegexKitLite來試用正則表達式 2. 使用YYText-文本藍色文字點擊實現超連接跳轉字體