From 327a83b8adc8a4e82569539c6ad7e5e83064c8c0 Mon Sep 17 00:00:00 2001 From: liyp Date: Sat, 7 Sep 2024 23:16:40 +0800 Subject: [PATCH] =?UTF-8?q?refactor(ai):=20=E6=94=B9=E8=BF=9B=20stripMarkd?= =?UTF-8?q?own=20=E5=87=BD=E6=95=B0=E4=BB=A5=E6=9B=B4=E5=85=A8=E9=9D=A2?= =?UTF-8?q?=E5=9C=B0=E5=A4=84=E7=90=86=20Markdown=20=E5=85=83=E7=B4=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- workers/ai.go | 48 ++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 42 insertions(+), 6 deletions(-) diff --git a/workers/ai.go b/workers/ai.go index 66a3b98..3d329e3 100644 --- a/workers/ai.go +++ b/workers/ai.go @@ -179,19 +179,55 @@ func (a *AI) GetMsg() string { } func stripMarkdown(text string) string { + + println("before:", text) // 移除代码块,但保留代码内容 - re := regexp.MustCompile("```(.*?)```") + re := regexp.MustCompile("(?s)```.*?```") + text = re.ReplaceAllStringFunc(text, func(match string) string { + return strings.TrimPrefix(strings.TrimSuffix(match, "```"), "```") + }) + + // 移除行内代码 + re = regexp.MustCompile("`([^`]+)`") text = re.ReplaceAllString(text, "$1") - // 移除粗体 - re = regexp.MustCompile(`\*\*(.*?)\*\*`) + // 移除标题 + re = regexp.MustCompile(`(?m)^#{1,6}\s+(.+)$`) text = re.ReplaceAllString(text, "$1") - // 移除下划线 - re = regexp.MustCompile("__(.*?)__") + // 移除粗体和斜体 + re = regexp.MustCompile(`(\*\*|__)(.+?)(\*\*|__)`) + text = re.ReplaceAllString(text, "$2") + re = regexp.MustCompile(`(\*|_)(.+?)(\*|_)`) + text = re.ReplaceAllString(text, "$2") + + // 移除链接,保留链接文本 + re = regexp.MustCompile(`\[([^\]]+)\]\([^\)]+\)`) text = re.ReplaceAllString(text, "$1") - return text + // 移除图片 + re = regexp.MustCompile(`!\[([^\]]*)\]\([^\)]+\)`) + text = re.ReplaceAllString(text, "$1") + + // 移除水平线 + re = regexp.MustCompile(`(?m)^-{3,}|_{3,}|\*{3,}$`) + text = re.ReplaceAllString(text, "") + + // 移除块引用 + re = regexp.MustCompile(`(?m)^>\s+(.+)`) + text = re.ReplaceAllString(text, "$1") + + // 移除列表标记 + re = regexp.MustCompile(`(?m)^[ \t]*[\*\-+][ \t]+`) + text = re.ReplaceAllString(text, "") + re = regexp.MustCompile(`(?m)^[ \t]*\d+\.[ \t]+`) + text = re.ReplaceAllString(text, "") + + // 移除多余的空行 + re = regexp.MustCompile(`\n{3,}`) + text = re.ReplaceAllString(text, "\n\n") + println("after:", text) + return strings.TrimSpace(text) } func getConfig() (string, string, string) {