我有点不愿意使用正则表达式给出答案,因为已经反复声明,使用正则表达式解析 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;">