需求:匹配文本内容中的标签,而后高亮显示出来。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-文本蓝色文字点击实现超连接跳转字体