我使用此代码使用RegEx将HTML字符串转换为NSAttributedString.我唯一的问题是嵌套的粗体和斜体标签.RegEx是正确的方法吗?
另外,我想避免使用HTML解析器,因为我需要的只有Bold,Italic和Underline属性以及StrikeThrough(如果可能).
有什么建议?
- (NSMutableAttributedString *)applyStylesToString:(NSString *)string searchRange:(NSRange)searchRange {
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:string];
[attributedString addAttribute:NSFontAttributeName value:[StylesConfig regularLargeFont] range:searchRange];
NSDictionary *boldAttributes = @{ NSFontAttributeName : [StylesConfig regularBoldLargeFont] };
NSDictionary *italicAttributes = @{ NSFontAttributeName : [StylesConfig regularItalicLargeFont] };
NSDictionary *underlineAttributes = @{ NSUnderlineStyleAttributeName : @1};
NSDictionary *strikeThroughAttributes = @{ NSStrikethroughStyleAttributeName : @1};
NSDictionary *replacements = @{
@"<b>(.*?)</b>" : boldAttributes,
@"<i>(.*?)</i>" : italicAttributes,
@"<u>(.*?)</u>" : underlineAttributes,
@"<s>(.*?)</s>" : strikeThroughAttributes
};
for (NSString *key in replacements) {
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:key …Run Code Online (Sandbox Code Playgroud)