您好我试图从Web响应中删除som HTML字符串。我想删除<pre><a style="" name="output-line-1">1</a>
,数字“1”的实例是否有所不同,但总是一个数字。但我怎么写正则表达式删除这个?以下是我到目前为止所得到的:
-(NSString *)stringByStrippingHTML:(NSString*)str
{
NSRange r;
while ((r = [str rangeOfString:@"/^<pre><a style=\"\"name=\"output-line-([0-9])\">([0-9])</a>" options:NSRegularExpressionSearch]).location != NSNotFound){
str = [str stringByReplacingCharactersInRange:r withString:@""];
}
}
基本上我想删除一个带有随机数的子字符串...在子字符串的某些实例中,1被替换,以便任何类似的字符串得到确认,例如它可以是output-line-999。如何组合字符串的范围,以便我可以描述字符串并指定查找任何类似的字符串?
我想删除HTML和数字。
答案 0 :(得分:1)
这个正则表达式应该有效:
[str rangeOfString:@"<pre><a style=\"\" name=\"output-line-[0-9]+\">[0-9]+</a>" options:NSRegularExpressionSearch];
我认为问题在于您的注册表达式中名称之前没有空格
答案 1 :(得分:0)
使用原始的while循环,您可以:
-(NSString *)stringByStrippingHTML:(NSString*)str
{
NSRange r;
while ((r = [str rangeOfString:@"<pre><a style=\"\" name=\"output-line-[0-9]+\">[0-9]+</a>" options:NSRegularExpressionSearch]).location != NSNotFound)
{
str = [str stringByReplacingCharactersInRange:r withString:@""];
}
}
或者您可以使用NSRegularExpression
:
NSMutableString *input = ...
NSError *error;
NSRegularExpression *regex;
regex = [NSRegularExpression regularExpressionWithPattern:@"<pre><a style=\"\" name=\"output-line-[0-9]+\">[0-9]+</a>"
options:0
error:&error];
if (error)
{
NSLog(@"error=%@",error);
return;
}
[regex replaceMatchesInString:input
options:0
range:NSMakeRange(0, [input length])
withTemplate:@""];