代码改变世界

oc 正则图片<img /> 标签

2016-04-07 16:24  xiangjune  阅读(425)  评论(0编辑  收藏  举报

 

 

-(NSString *)getImageAttributeValue:(NSString *)content attributeKey:(NSString *)key {

    NSString *regexString = [NSString stringWithFormat:@"%@=\\\"(.*?)\\\"", key];

    NSRange range = [content rangeOfString:regexString options:NSRegularExpressionSearch];

    if (range.location != NSNotFound) {

        return [[content substringWithRange:range] componentsSeparatedByString:@"\""][1];

    } else {

        return nil;

    }

}

 

-(NSString *)filterFormularCodeTag:(NSMutableString *)htmlString

{

    NSString *content = htmlString;

    

    NSString *regexString = [NSString stringWithFormat:@"<img(.*?)code=(.*?)[^>]*?>"];

    NSError *error = nil;

    NSRegularExpression *regular = [NSRegularExpression regularExpressionWithPattern:regexString options:NSRegularExpressionCaseInsensitive error:&error];

    NSArray *resultArray = [regular matchesInString:htmlString options:0 range:NSMakeRange(0, [htmlString length])];

    for (NSTextCheckingResult *result in resultArray)

    {

        NSString *subString = [htmlString substringWithRange:result.range];

        NSString *codeContent = [self getImageAttributeValue:subString attributeKey:@"code"];

        

        content = [content stringByReplacingOccurrencesOfString:subString withString:codeContent];

    }

    

    return content;

}