开发者社区 问答 正文

替换变量子字符串

字符串如下:<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

展开
收起
爵霸 2016-03-24 09:41:41 1991 分享 版权
1 条回答
写回答
取消 提交回答
  • 下面的方法使用 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]];
    }
    2019-07-17 19:11:57
    赞同 展开评论
问答地址: