0

我有一些包含一些 img 标签的 html 数据,如下所示:

img width=500 height=400
img width=400 height=250
img width=600 height=470

高度和宽度总是在变化。我必须替换该html数据。我需要使用 Objective-C 将该 html 数据替换为“img with=100”。

我写了这些,但它不匹配

NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"/(img\\s)((width|height)(=)([0-9]+)"
                                                                       options:NSRegularExpressionCaseInsensitive
                                                                         error:&error];
NSUInteger numberOfMatches = [regex numberOfMatchesInString:myhtmldata
                                                    options:0
                                                      range:NSMakeRange(0, [myhtmldata length])];

NSString *modifiedString; 
if (numberOfMatches > 0)
{
   modifiedString = [regex stringByReplacingMatchesInString:myhtmldata
                                                           options:0
                                                             range:NSMakeRange(0, [myhtmldata length])
                                                      withTemplate:@"img width=30"];

}

你能帮助我吗 ?

4

2 回答 2

2

如果我从您的示例代码中正确推断出意图,您只想使用NSRegularExpression将宽度更改为 30。然后:

#import <Foundation/Foundation.h>

int main(int argc, char *argv[]) {
    @autoreleasepool {
        NSError *regexError = nil;
        NSRegularExpressionOptions options = 0;
        NSString *sampleText = @"img width=500 height=400";
        NSString *pattern = @"^(img\\s+)width=\\d+(\\s+height=\\d+)";
        NSRegularExpression *expression = [NSRegularExpression regularExpressionWithPattern:pattern options:options error:&regexError];

        sampleText = [expression stringByReplacingMatchesInString:sampleText
                                                          options:0
                                                            range:NSMakeRange(0,sampleText.length)
                                                     withTemplate:@"$1width=30$2"];
        printf("%s\n",[sampleText UTF8String]);
    }

}

打印img width=30 height=400到控制台。

编辑:

您更改更改正确转义时的正则表达式(img\s+width=)\d+\s+height=\d+将是:

@"(img\\s+width=)\\d+\\s+height=\\d+"

然后将模板字符串更改为@"$130". 如果您对我的原始代码进行了这些更改,您应该匹配所有出现img在 HTML 中的标记。例如,它应该改变:

<html>
    <body>
        <img width=500 height=400>
        <img width=520 height=100>
    </body>
</html>

至:

<html>
    <body>
        <img width=30>
        <img width=30>
    </body>
</html>

这是您的规格要求的吗?

于 2012-12-09T04:47:42.023 回答
0

我找到了一种不同的方法,它正在工作。这是代码:

NSArray* ary = [oldHtml componentsSeparatedByString:@"<img"];
NSString* newHtml = [ary objectAtIndex:0];
for (int i = 1; i < [ary count]; i++) {

    newHtml = [newHtml stringByAppendingString:[@"<img width=300 " stringByAppendingString:[[ary objectAtIndex:i] substringFromIndex:[[ary objectAtIndex:i] rangeOfString:@"src"].location]]];

}
于 2012-12-09T23:14:37.387 回答