iOS:Strip< img ...>来自NSString(一个html字符串) [英] iOS: Strip <img...> from NSString (a html string)
问题描述
NSString
,它基本上是一个 html
字符串,其中所有通常的 html
元素。我想要做的具体事情是将其从所有 img
标签中剥离。 img
标签可能有或没有最大宽度,样式或其他属性,所以我不知道它们的长度。他们总是以 /> gt结尾
我怎么能这样做?
编辑:基于 nicolasthenoz
的答案,我提出了一个需要较少代码的解决方案:
NSString * HTMLTagss = @< img [^> *>; //正则表达式去除img标签
NSString * stringWithoutImage = [htmlString stringByReplacingOccurrencesOfRegex:HTMLTagss withString:@];
解决方案您可以使用 NSString 方法 stringByReplacingOccurrencesOfString
与 NSRegularExpressionSearch
选项:
NSString * result = [html stringByReplacingOccurrencesOfString:@< img [^>] *> withString:@选项:NSCaseInsensitiveSearch | NSRegularExpressionSearch范围: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 code> RegexKitLite
的方法。没有必要为这样简单的事情引入第三方库,除非有其他引人注目的问题。
So I have an NSString
which is basically an html
string with all the usual html
elements. The specific thing I would like to do is to just strip it from all the img
tags.
The img
tags may or may not have max-width, style or other attributes so I do not know their length up front. They always end with />
How could I do this?
EDIT: Based on nicolasthenoz
's answer, I came up with a solution that requires less code:
NSString *HTMLTagss = @"<img[^>]*>"; //regex to remove img tag
NSString *stringWithoutImage = [htmlString stringByReplacingOccurrencesOfRegex:HTMLTagss withString:@""];
解决方案 You can use the NSString
method stringByReplacingOccurrencesOfString
with the NSRegularExpressionSearch
option:
NSString *result = [html stringByReplacingOccurrencesOfString:@"<img[^>]*>" withString:@"" options:NSCaseInsensitiveSearch | NSRegularExpressionSearch range:NSMakeRange(0, [html length])];
Or you can also use the replaceMatchesInString
method of NSRegularExpression
. Thus, assuming you have your html in a NSMutableString *html
, you can:
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"<img[^>]*>"
options:NSRegularExpressionCaseInsensitive
error:nil];
[regex replaceMatchesInString:html
options:0
range:NSMakeRange(0, html.length)
withTemplate:@""];
I'd personally lean towards one of these options over the stringByReplacingOccurrencesOfRegex
method of RegexKitLite
. There's no need to introduce a third-party library for something as simple as this unless there was some other compelling issue.
这篇关于iOS:Strip< img ...>来自NSString(一个html字符串)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!