[英]iOS: Strip <img…> from NSString (a html string)
所以我有一个NSString
,它基本上是一个包含所有常用html
元素的html
字符串。 我想做的具体事情就是从所有img
标签中删除它。 img
标签可能有也可能没有最大宽度、样式或其他属性,所以我不知道它们的长度。 他们总是以/>
结尾
我怎么能这样做?
编辑:基于nicolasthenoz
的回答,我想出了一个需要更少代码的解决方案:
NSString *HTMLTagss = @"<img[^>]*>"; //regex to remove img tag
NSString *stringWithoutImage = [htmlString stringByReplacingOccurrencesOfRegex:HTMLTagss withString:@""];
您可以将NSString
方法stringByReplacingOccurrencesOfString
与NSRegularExpressionSearch
选项一起使用:
NSString *result = [html stringByReplacingOccurrencesOfString:@"<img[^>]*>" withString:@"" options:NSCaseInsensitiveSearch | NSRegularExpressionSearch range:NSMakeRange(0, [html length])];
或者你也可以使用replaceMatchesInString
的方法NSRegularExpression
。 因此,假设您将 html 放在NSMutableString *html
,您可以:
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"<img[^>]*>"
options:NSRegularExpressionCaseInsensitive
error:nil];
[regex replaceMatchesInString:html
options:0
range:NSMakeRange(0, html.length)
withTemplate:@""];
我个人的偏向这些选项在一个stringByReplacingOccurrencesOfRegex
的方法RegexKitLite
。 除非有其他一些引人注目的问题,否则没有必要为这样简单的事情引入第三方库。
使用正则表达式,找到字符串中的匹配项并删除它们! 这是如何
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"<img[^>]*>"
options:NSRegularExpressionCaseInsensitive
error:nil];
NSMutableString* mutableString = [yourStringToStripFrom mutableCopy];
NSInteger offset = 0; // keeps track of range changes in the string due to replacements.
for (NSTextCheckingResult* result in [regex matchesInString:yourStringToStripFrom
options:0
range:NSMakeRange(0, [yourStringToStripFrom length])]) {
NSRange resultRange = [result range];
resultRange.location += offset;
NSString* match = [regex replacementStringForResult:result
inString:mutableString
offset:offset
template:@"$0"];
// make the replacement
[mutableString replaceCharactersInRange:resultRange withString:@""];
// update the offset based on the replacement
offset += ([match length] - resultRange.length);
}
您可以在 Swift 4,5 中使用以下函数:
func filterImgTag(text: String) -> String{
return text.replacingOccurrences(of: "<img[^>]*>", with: "", options: String.CompareOptions.regularExpression)
}
希望能帮到大家! 如果它对你有用,请在下面评论。 谢谢。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.