0

我有这个字符串:<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

4

2 回答 2

3

以下代码使用NSRegularExpression类来替换 divs HTML 标记的宽度样式属性(当以您指定的格式提供时):

// 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]];
}
于 2013-03-30T21:18:40.837 回答
1

使用正则表达式:string.replace(/width:\s*\d+px/, 'width: 275px')

编辑:再想一想,如果这只是更大字符串的一部分,您可能不想用275px(或260px)替换所有宽度。您仍然应该使用正则表达式,但我不确定在没有看到它所在的上下文以及知道您做什么和不想替换的情况下它会寻找什么。

于 2013-03-30T18:34:45.807 回答