iOS OC使用正则表达式去除特殊符号并加粗文本,适用于接入AI大模型的流模式数据的文字处理

1、编写逻辑

使用分类(Category)的方法拓展NSString,本文使用NSString (Markdown),NSString的分类来编写一个通用方法,使用正则表达式匹配字符串实现去除特殊字符,并自定义文字属性。

在接入AI大模型后,返回的字符串会带有特殊字符用于做文字处理,下面代码简单进行了文字处理展示。

2、代码实现

1、NSString+Markdown.h

复制代码
#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN

@interface NSString (Markdown)

- (NSAttributedString *)attributedStringFromMarkdown;

@end

NS_ASSUME_NONNULL_END

2、NSString+Markdown.m

文中做了处理 ### 与 **加粗文本** 的处理,可根据需求进行拓展

复制代码
#import "NSString+Markdown.h"

static NSRegularExpression *_headerRegex;
static NSRegularExpression *_boldRegex;
static dispatch_once_t onceToken;

@implementation NSString (Markdown)

- (NSAttributedString *)attributedStringFromMarkdown {
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:self];
    // 设置默认字体,做自适应高度时,必须要设置默认字体
    UIFont *defaultFont = [UIFont systemFontOfSize:20];
    [attributedString addAttribute:NSFontAttributeName value:defaultFont range:NSMakeRange(0, attributedString.length)];
    // 一次性初始化正则表达式
    dispatch_once(&onceToken, ^{
        NSError *error;
        // 匹配 ### 标题
        _headerRegex = [NSRegularExpression regularExpressionWithPattern:@"^###\\s*(.*?)\\s*(?=\n)"
                                                                 options:NSRegularExpressionAnchorsMatchLines
                                                                   error:&error];
        if (error) {
            NSLog(@"### 正则表达式初始化失败: %@", error.localizedDescription);
        }
        
        // 匹配 **加粗文本**
        _boldRegex = [NSRegularExpression regularExpressionWithPattern:@"\\*\\*(.*?)\\*\\*"
                                                               options:0
                                                                 error:&error];
        if (error) {
            NSLog(@"** 正则表达式初始化失败: %@", error.localizedDescription);
        }
    });
    
    // 处理 "### 标题" 的加粗,并去掉 "###"
    NSArray *headerMatches = [_headerRegex matchesInString:attributedString.string
                                                   options:0
                                                     range:NSMakeRange(0, attributedString.length)];
    
    for (NSTextCheckingResult *match in [headerMatches reverseObjectEnumerator]) {
        NSRange fullMatchRange = match.range;          // 包含 ### 的完整匹配范围
        NSRange contentRange = [match rangeAtIndex:1]; // 实际要加粗的内容
        
        if (contentRange.location != NSNotFound) {
            // 1️⃣ 应用加粗样式
            [attributedString addAttributes:@{
                NSFontAttributeName: [UIFont boldSystemFontOfSize:20]
            } range:contentRange];
            
            // 2️⃣ 替换 "### 标题" 只保留标题文本
            NSString *content = [attributedString.string substringWithRange:contentRange];
            [attributedString replaceCharactersInRange:fullMatchRange withString:content];
            
            
            // 3️⃣重新获取新文本的位置
            NSRange newRange = NSMakeRange(fullMatchRange.location, content.length);
            // 重新加粗
            [attributedString addAttributes:@{
                NSFontAttributeName: [UIFont boldSystemFontOfSize:20]
            } range:newRange];
            
        }
    }

    // 处理 "**加粗文本**" 的加粗,并去掉 "**"
    NSArray *boldMatches = [_boldRegex matchesInString:attributedString.string
                                               options:0
                                                 range:NSMakeRange(0, attributedString.length)];
    
    for (NSTextCheckingResult *match in [boldMatches reverseObjectEnumerator]) {
        NSRange fullMatchRange = match.range;          // 包含 ** 的完整匹配范围
        NSRange contentRange = [match rangeAtIndex:1]; // 实际要加粗的内容
        
        if (contentRange.location != NSNotFound) {
            // 1️⃣ 应用加粗样式
            [attributedString addAttributes:@{
                NSFontAttributeName: [UIFont boldSystemFontOfSize:20]
            } range:contentRange];
            
            // 2️⃣ 替换 "**加粗文本**" 只保留加粗文本
            NSString *content = [attributedString.string substringWithRange:contentRange];
            [attributedString replaceCharactersInRange:fullMatchRange withString:content];
            
            // 3️⃣重新获取新文本的位置
            NSRange newRange = NSMakeRange(fullMatchRange.location, content.length);
            // 重新加粗
            [attributedString addAttributes:@{
                NSFontAttributeName: [UIFont boldSystemFontOfSize:20]
            } range:newRange];
        }
    }

    return attributedString;
}

@end

3、调用方法

复制代码
NSString *text = [message.text attributedStringFromMarkdown].string;
相关推荐
美狐美颜sdk1 小时前
什么是美颜SDK?美颜SDK安卓与iOS端开发指南
android·人工智能·ios·音视频·美颜sdk·直播美颜sdk
北极有牛2 小时前
cpp学习笔记2--class
c++·笔记·学习
Non importa2 小时前
【初阶数据结构】树——二叉树——堆(中)
java·c语言·数据结构·学习·算法
Jet45052 小时前
第100+40步 ChatGPT学习:R语言实现多轮建模
学习·chatgpt·r语言·多轮建模
A_aspectJ3 小时前
【Bootstrap V4系列】学习入门教程之 组件-卡片(Card)高级用法
前端·学习·bootstrap
jz_ddk3 小时前
[学习]RTKLib详解:rtkcmn.c与rtkpos.c
c语言·学习·算法
虾球xz4 小时前
游戏引擎学习第261天:切换到静态帧数组
c++·学习·游戏引擎
霖005 小时前
FPGA实战项目1——坦克大战
人工智能·经验分享·嵌入式硬件·学习·fpga开发·fpga
Lucky高5 小时前
学习Python网络爬虫的实例
爬虫·python·学习
一只码代码的章鱼5 小时前
5.4学习记录
学习·算法·动态规划