Compare commits

...

3 Commits

Author SHA1 Message Date
CJACK.
27eb73d48b Merge pull request #346 from CJackHwang/dev
Normalize string tool inputs and enhance schema protection
2026-04-28 22:06:41 +08:00
CJACK.
685b5011e4 Merge pull request #343 from livesRan/fix-429Resend-pr
支持 reference 引用标签转链接,并兼容 0 基序号映射
2026-04-28 21:47:15 +08:00
songguoliang
15e9eb3639 支持 reference 引用标签转链接,并兼容 0 基序号映射 2026-04-28 16:42:37 +08:00
2 changed files with 38 additions and 5 deletions

View File

@@ -26,3 +26,31 @@ func TestReplaceCitationMarkersWithLinksKeepsUnknownIndex(t *testing.T) {
t.Fatalf("expected %q, got %q", want, got) t.Fatalf("expected %q, got %q", want, got)
} }
} }
func TestReplaceCitationMarkersWithLinksSupportsReferenceMarker(t *testing.T) {
raw := "新闻摘要[reference:1],详情[reference:2]。"
links := map[int]string{
1: "https://example.com/r1",
2: "https://example.com/r2",
}
got := replaceCitationMarkersWithLinks(raw, links)
want := "新闻摘要[1](https://example.com/r1),详情[2](https://example.com/r2)。"
if got != want {
t.Fatalf("expected %q, got %q", want, got)
}
}
func TestReplaceCitationMarkersWithLinksSupportsReferenceZeroBased(t *testing.T) {
raw := "来源[reference:0] 与 [reference:1]。"
links := map[int]string{
1: "https://example.com/first",
2: "https://example.com/second",
}
got := replaceCitationMarkersWithLinks(raw, links)
want := "来源[0](https://example.com/first) 与 [1](https://example.com/second)。"
if got != want {
t.Fatalf("expected %q, got %q", want, got)
}
}

View File

@@ -7,22 +7,27 @@ import (
"strings" "strings"
) )
var citationMarkerPattern = regexp.MustCompile(`(?i)\[citation:\s*(\d+)\]`) var citationMarkerPattern = regexp.MustCompile(`(?i)\[(citation|reference):\s*(\d+)\]`)
func ReplaceCitationMarkersWithLinks(text string, links map[int]string) string { func ReplaceCitationMarkersWithLinks(text string, links map[int]string) string {
if strings.TrimSpace(text) == "" || len(links) == 0 { if strings.TrimSpace(text) == "" || len(links) == 0 {
return text return text
} }
zeroBased := strings.Contains(strings.ToLower(text), "[reference:0]")
return citationMarkerPattern.ReplaceAllStringFunc(text, func(match string) string { return citationMarkerPattern.ReplaceAllStringFunc(text, func(match string) string {
sub := citationMarkerPattern.FindStringSubmatch(match) sub := citationMarkerPattern.FindStringSubmatch(match)
if len(sub) < 2 { if len(sub) < 3 {
return match return match
} }
idx, err := strconv.Atoi(strings.TrimSpace(sub[1])) idx, err := strconv.Atoi(strings.TrimSpace(sub[2]))
if err != nil || idx <= 0 { if err != nil || idx < 0 {
return match return match
} }
url := strings.TrimSpace(links[idx]) lookupIdx := idx
if zeroBased {
lookupIdx = idx + 1
}
url := strings.TrimSpace(links[lookupIdx])
if url == "" { if url == "" {
return match return match
} }