当前位置: 首页 > news >正文

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;

相关文章:

  • 深度学习 Deep Learning 第1章 深度学习简介
  • ByteByteGo学习笔记:通知系统设计
  • Redis分布式锁深度剖析:从原理到Redisson实战,破解脑裂与高并发锁难题
  • jupyter无法转换为PDF,HTMLnbconvert failed: Pandoc wasn‘t found.
  • 如何更新 Oh My Zsh
  • k8s中的控制器的使用
  • NetLink内核套接字案例分析
  • 黄金还能再涨吗?
  • 虚拟健身教练小程序:AI动作识别与个性化训练计划生成
  • 3.14周报
  • 联想拯救者 M600 无线游戏鼠标|自定义驱动程序安装说明
  • 研究整除的性质——最大公约数(GCD)和最小公倍数(LCM)
  • JavaScript基础-作用域概述
  • 【品铂科技工业生产应用案例解析】
  • 使用DeepSeek制作可视化图表和流程图
  • vue处理接口返回EventStream数据并进行展示
  • TI的Doppler-Azimuth架构(TI文档)
  • 负载均衡中四层和七层协议区别
  • 机器人触觉的意义
  • mysql学习-删除数据(drop、truncate、delete)
  • 俄乌上周在土耳其直接谈判,外交部回应
  • 上千螺母引发的枪支散件案:五金厂老板的儿子被诉,律师作无罪辩护
  • 国家统计局:2024年城镇单位就业人员工资平稳增长
  • 武大校长:人工智能不存在“过度使用”,武大不会缩减文科
  • 龚正会见哥伦比亚总统佩特罗
  • 1至4月全国铁路发送旅客14.6亿人次,创同期历史新高