HTMLを正規表現で解析することは、有害、不可能、心に危険などと見なされると繰り返し述べられているため、正規表現を使用して答えるのは少し気が進まない。それはすべて正しいが、主張するつもりはない。何か違う。
しかし、そのすべての警告の後でも、OPは明示的に正規表現ソリューションを要求しているので、このコードを共有します。少なくとも、正規表現のすべての一致をループすることによって文字列を変更する方法の例として役立ちます。
NSString *htmlString =
@"<div style=\"font-family:'Arial';font-size:43px;color:#ffffff;\">\n"
@"<div style=\"font-size:12px;\">\n";
NSRegularExpression *regex;
regex = [NSRegularExpression regularExpressionWithPattern:@"font-size:([0-9]+)px;"
options:0
error:NULL];
NSMutableString *modifiedHtmlString = [htmlString mutableCopy];
__block int offset = 0;
[regex enumerateMatchesInString:htmlString
options:0
range:NSMakeRange(0, [htmlString length])
usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {
// range = location of the regex capture group "([0-9]+)" in htmlString:
NSRange range = [result rangeAtIndex:1];
// Adjust location for modifiedHtmlString:
range.location += offset;
// Get old point size:
NSString *oldPointSize = [modifiedHtmlString substringWithRange:range];
// Compute new point size:
NSString *newPointSize = [NSString stringWithFormat:@"%.1f", [oldPointSize floatValue]/2];
// Replace point size in modifiedHtmlString:
[modifiedHtmlString replaceCharactersInRange:range withString:newPointSize];
// Update offset:
offset += [newPointSize length] - [oldPointSize length];
}
];
NSLog(@"%@", modifiedHtmlString);
出力:
<div style="font-family:'Arial';font-size:21.5px;color:#ffffff;">
<div style="font-size:6.0px;">