iOS:从NSString(一个htmlstring)剥离<img …>

所以我有一个NSString ,它基本上是一个包含所有常用html元素的htmlstring。 我想要做的具体事情就是从所有的img标签中删除它。 img标签可能有或没有最大宽度,样式或其他属性,所以我不知道它们的长度。 他们总是以/>结尾

我怎么能这样做?

编辑:根据nicolasthenoz的答案,我想出了一个解决scheme,需要较less的代码:

 NSString *HTMLTagss = @"<img[^>]*>"; //regex to remove img tag NSString *stringWithoutImage = [htmlString stringByReplacingOccurrencesOfRegex:HTMLTagss withString:@""]; 

您可以使用NSString方法stringByReplacingOccurrencesOfStringNSRegularExpressionSearch选项:

 NSString *result = [html stringByReplacingOccurrencesOfString:@"<img[^>]*>" withString:@"" options:NSCaseInsensitiveSearch | NSRegularExpressionSearch range:NSMakeRange(0, [html length])]; 

或者你也可以使用replaceMatchesInString方法。 因此,假设你有一个NSMutableString *html ,你可以:

 NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"<img[^>]*>" options:NSRegularExpressionCaseInsensitive error:nil]; [regex replaceMatchesInString:html options:0 range:NSMakeRange(0, html.length) withTemplate:@""]; 

我个人倾向于stringByReplacingOccurrencesOfRegex方法的这些选项RegexKitLite 。 没有必要为这样简单的事情引入第三方库,除非存在其他一些令人信服的问题。

使用一个正则expression式,find你的string中的匹配,并删除它们! 这是如何

 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 += ([replacement length] - resultRange.length); }