匹配字符串中的tag部分,提取tag的内容,和属性的值
- (void)viewDidLoad {
[super viewDidLoad];
NSString *searchText = @"<font id='J19061815234482' color='#3b7fe0'>lvluo851</font>";
[self getContentWithHtmlString: searchText tag:@"font" attribute:@"id"];
}
/**
得到html某标签的内容和标签的属性值
@param htmlString html标签字符串
@param tag 标签名,如font
@param attr 标签的属性字段,如 id
*/
- (void)getContentWithHtmlString:(NSString*)htmlString tag:(NSString*)tag attribute:(NSString*)attr{
NSString *reg = @"<%@[^<>]*?\\s%@=['\"]?(.*?)['\"]?\\s.*?>([^<]*)</%@>";
reg = [NSString stringWithFormat:reg, tag,attr,tag];
NSString *searchText = htmlString;
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:reg options:NSRegularExpressionCaseInsensitive error:&error];
NSArray *matches =
[regex matchesInString:searchText options:0 range:NSMakeRange(0, searchText.length)];
for( NSTextCheckingResult *result in matches ){
//提取正则中()中的分组匹配到的字符串的值,也就是属性值与 标签值
if (result) {
NSLog(@"attr=%@", [searchText substringWithRange:[result rangeAtIndex:1]]);
NSLog(@"content=%@", [searchText substringWithRange:[result rangeAtIndex:2]]);
}
}
}
以上方法打印结果:
2019-11-21 08:58:10.126559+0800 TestTag[33742:1697297] attr=J19061815234482
2019-11-21 08:58:10.126767+0800 TestTag[33742:1697297] content=lvluo851