iOS去掉字符串中的HTML标签的方法

方法一、NSScanner去除标签

 1 - (NSString *)removeTheHtmlFromString:(NSString *)htmlString {
 2     NSScanner * scanner = [NSScanner scannerWithString:htmlString];
 3     NSString * text = nil;
 4     while([scanner isAtEnd]==NO) {
 5         //找到标签的起始位置
 6         [scanner scanUpToString:@"<" intoString:nil];
 7         //找到标签的结束位置
 8         [scanner scanUpToString:@">" intoString:&text];
 9         //替换字符
10         htmlString = [htmlString stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%@>",text] withString:@""];
11     }
12     return htmlString;
13 }

方法二、正则方法

1 //正则去除标签
2 -(NSString *)removeHtmlWithString:(NSString *)htmlString{
3     NSRegularExpression * regularExpretion=[NSRegularExpression regularExpressionWithPattern:@"<[^>]*>|\n" options:0 error:nil];
4     htmlString = [regularExpretion stringByReplacingMatchesInString:htmlString options:NSMatchingReportProgress range:NSMakeRange(0, htmlString.length) withTemplate:@""];
5     return htmlString;
6 }

 

posted @ 2019-09-01 16:05  独处守心  阅读(1714)  评论(0编辑  收藏  举报