UE5 处理Markdown标记文本

项目中Dify和混元的AI的回答长篇会返回markdown标记的内容,貌似只能摘掉,没找到可以显示的插件之类的,只能封装一个去除Markdown标记的蓝图节点。

一、实现思路

第一步:按行处理markdown行前缀

std::istringstream reader(input);
while (std::getline(reader, line)) {
    ...
    lines.push_back(line);
}

注意要转换为UTF-8字符串方便用标准库进行处理

std::string input = TCHAR_TO_UTF8(*InputMarkdown);

处理Markdown常见前缀格式

Markdown条件处理方式
#line.rfind("# ", 0) == 0只保留标题文本内容
>line.rfind("> ", 0) == 0去掉引用前缀
- 、* 、+line.rfind("- ", 0) == 0 等去掉列表前缀

line.substr(…) 的作用是去掉前缀,只保留内容

第二步:处理行内Markdown标记

result = std::regex_replace(result, std::regex(R"(\!\[[^\]]*\]\([^\)]*\))"), "");
result = std::regex_replace(result, std::regex(R"(\[([^\]]*)\]\([^\)]*\))"), "$1");
result = std::regex_replace(result, std::regex(R"(`([^`]*)`)"), "$1");
正则表达式匹配内容替换后结果
!..(…)图片语法删除整个内容
…(…)超链接只保留“文字”部分
``行内代码只保留代码

第三步:去除装饰符(*和_)

for (char c : result) {
    if (c == '*' || c == '_') continue;
    finalText += c;
}

二、完整代码

UFUNCTION(BlueprintCallable, Category = "Text Utilities")
static FString StripMarkdown(const FString& InputMarkdown);
FString UMyBlueprintFunctionLibrary::StripMarkdown(const FString& InputMarkdown)
{
    std::string input = TCHAR_TO_UTF8(*InputMarkdown);
    std::vector<std::string> lines;
    std::string line;
    std::istringstream reader(input);

    // 1. 逐行处理
    while (std::getline(reader, line)) {
       if (line.rfind("# ", 0) == 0 || line.rfind("## ", 0) == 0 || 
          line.rfind("### ", 0) == 0 || line.rfind("#### ", 0) == 0 || 
          line.rfind("##### ", 0) == 0 || line.rfind("###### ", 0) == 0)
       {
          line = line.substr(line.find(' ') + 1);
       }
       else if (line.rfind("> ", 0) == 0) {
          line = line.substr(2);
       }
       else if (line.rfind("- ", 0) == 0 || line.rfind("* ", 0) == 0 || line.rfind("+ ", 0) == 0)
       {
          line = line.substr(2);
       }
       lines.push_back(line);
    }

    std::string result;
    for (size_t i = 0; i < lines.size(); ++i) {
       result += lines[i];
       if (i + 1 < lines.size()) result += '\n';
    }

    // 2. 使用正则清理行内 Markdown
    result = std::regex_replace(result, std::regex(R"(\!\[[^\]]*\]\([^\)]*\))"), "");
    result = std::regex_replace(result, std::regex(R"(\[([^\]]*)\]\([^\)]*\))"), "$1");
    result = std::regex_replace(result, std::regex(R"(`([^`]*)`)"), "$1");

    // 3. 去掉 * 和 _
    std::string finalText;
    finalText.reserve(result.size());
    for (char c : result) {
       if (c == '*' || c == '_') continue;
       finalText += c;
    }

    return UTF8_TO_TCHAR(finalText.c_str());
}

最后使用
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值