Go 提取字符串中url,转换为markdown格式并替换

 

Go 提取字符串中url,转换为markdown格式并替换

// MakeContentUrlToMarkDown 将字符串中url非markdown格式转[](url)格式
func MakeContentUrlToMarkDown(sourceString string) (resultString string) {
    //urlReMustCompile := regexp.MustCompile(".*(?P<URL>(http|https|ftp):\\/\\/)?((|[\\w-]+\\.)+[a-z0-9]+)(?:(\\/[^/?#]+)*)?(\\?[^#]+)?(#.+)?))")
    urlReMustCompile := regexp.MustCompile(".*[^\\[]+[^\\(]+(?P<URL>((https?://[^\\s]+)([0-9]+|[a-z]+|[A-Z]+|[$+_/=?%]+)+))")
    for urlReMustCompile.MatchString(sourceString) {
        match := urlReMustCompile.FindStringSubmatch(sourceString)
        groupNames := urlReMustCompile.SubexpNames()
        // 转换为map
        for i, name := range groupNames {
            if i != 0 && name != "" { // 第一个分组为空(也就是整个匹配)
                urlString := match[i]
                newUrlMarkdownString := "[点击链接查看](" + urlString + ")"
                sourceString = strings.ReplaceAll(sourceString, urlString, newUrlMarkdownString)
            }
        }
    }
    resultString = sourceString
    return
}
bodyContent9 := "BJ-SC-DC-TOR-186.BJ单slot替换-控制台主机列表http://www.kdocs.cn/l/?a=b&b=ccc&D=cde2bbfJhtyb#testx1国家  访问http://www.kdocs.cn/l/aaax=bc dfasdf"
markdownTestResult := MakeContentUrlToMarkDown(bodyContent9)
fmt.Println("markdownTestResult:", markdownTestResult)
效果:
markdownTestResult: BJ-SC-DC-TOR-186.BJ单slot替换-控制台主机列表[点击链接查看](http://www.kdocs.cn/l/?a=b&b=ccc&D=cde2bbfJhtyb#testx1)国家 访问[点击链接查看](http://www.kdocs.cn/l/aaax=bc) dfasdf

 

posted on 2023-10-17 22:34  zhangmingda  阅读(70)  评论(0编辑  收藏  举报

导航