项目中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());
}
最后使用