次のコードは、NSRegularExpressionクラスを使用して、指定した形式で提供された divs HTML マークアップの width スタイル属性を置き換えます。
// 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]];
}