替换变量子字符串

字符串如下:<div id="attachment_16696" class="wp-caption alignnone" style="width: 460px">

我希望的是:<div id="attachment_16696" class="wp-caption alignnone" style="width: 275px">

我都实现的差不多了,还有一个问题,比如,如果是 1000px ,因为不匹配就无法实现。

怎么样能让虽然不是 460px ,但是我能操作成 260px

下面的方法使用 NSRegularExpression 类修改HTMLdiv标记的宽度类型属性:

// Takes Div markup in the following formats:
// <div id="something" class="something" style="width: Xpx">
// <div id="something" class="something" width="X">
// And replaces X with desired value.
- (NSString *)setDivMarkup:(NSString *)markup width:(NSInteger)width
{
    NSString *regexToReplaceWidth = @"width(:|=)(\")?\\s*\\d+\\s*(px)?";

    NSError *error = NULL;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regexToReplaceWidth
                                                                           options:NSRegularExpressionCaseInsensitive
                                                                             error:&error];

    return [regex stringByReplacingMatchesInString:markup
                                           options:0
                                             range:NSMakeRange(0, markup.length)
                                      withTemplate:[NSString stringWithFormat:@"width$1$2%d$3", width]];
}