我有以下方法从字符串中删除html标记和不需要的字符:
-(NSString *) stringByStrippingHTML: (NSString*) s {
NSRange r;
while ((r = [s rangeOfString:@"<[^>]+>" options:NSRegularExpressionSearch]).location != NSNotFound)
s = [s stringByReplacingCharactersInRange:r withString:@""];
while ((r = [s rangeOfString:@"’" options:NSRegularExpressionSearch]).location != NSNotFound)
s = [s stringByReplacingCharactersInRange:r withString:@"\'"];
while ((r = [s rangeOfString:@"”" options:NSRegularExpressionSearch]).location != NSNotFound)
s = [s stringByReplacingCharactersInRange:r withString:@"\""];
while ((r = [s rangeOfString:@"“" options:NSRegularExpressionSearch]).location != NSNotFound)
s = [s stringByReplacingCharactersInRange:r withString:@"\""];
while ((r = [s rangeOfString:@"…" options:NSRegularExpressionSearch]).location != NSNotFound)
s = [s stringByReplacingCharactersInRange:r withString:@"..."];
while ((r = [s rangeOfString:@"–" options:NSRegularExpressionSearch]).location != NSNotFound)
s = [s stringByReplacingCharactersInRange:r withString:@"-"];
return s;
}
我有太多的情况,怎么能以更优雅的方式完成?
答案 0 :(得分:1)
我相信NSString
有一些内置的方法。 Check this answer out.
答案 1 :(得分:1)
google-toolbox-for-mac库(是的,这也适用于iOS)有一些NSString
类别方法,可以更有效地转义&符号编码字符。看看GTMNSString+HTML。
这不会处理第一种情况(剥离HTML标记),但对于您正在进行的其他替换,它应该是一种更快,更全面的解决方案。
答案 2 :(得分:0)
除第一种情况外,你可以像[s stringByReplacingOccurrencesOfString:"”" withString:@"\""];
一样使用。