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

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;


http://www.kler.cn/a/591963.html

相关文章:

  • CES Asia2025:以科技创新奖为核心,重塑展位战略价值
  • Opencv之计算机视觉一
  • 网络空间安全(34)安全防御体系
  • Python----数据分析(Pandas二:一维数组Series,Series的创建,Series的属性,Series中元素的索引与访问)
  • 【redis】什么是持久化之 RDB
  • TypeScript中的类型断言(type assertion),如何使用类型断言进行类型转换?
  • R语言零基础系列教程-03-RStudio界面介绍与关键设置
  • DeepSeek关键技术再总结
  • DNS解析查询工具
  • 设计模式(行为型)-观察者模式
  • Android第四次面试(Java基础篇)
  • 机器学习——深入浅出理解朴素贝叶斯算法
  • Redis项目:短信验证码登录
  • 【JDK17】开源应用服务器大比对
  • logparser日志分析详解
  • ubuntu20.04安装mysql-workbench
  • DataWhale 大语言模型 - 模型详细配置
  • conda 的 envs_dirs 配置出错
  • 解决 ECharts 切换图表时的 Resize 问题
  • 博客图床 VsCode + PicGo + 阿里云OSS