如何用 Golang 正则表达式中的参数替换所有内容?

我正在使用 Golang 正则表达式包,我想使用带有参数的正则表达式 ReplaceAllStringFunc,而不仅仅是源字符串。


例如,我想更新此文本


"<img src=\"/m/1.jpg\" />  <img src=\"/m/2.jpg\" />  <img src=\"/m/3.jpg\" />"

To(将“m”更改为“a”或其他任何内容):


"<img src=\"/a/1.jpg\" />  <img src=\"/a/2.jpg\" />  <img src=\"/a/3.jpg\" />"

我想要类似的东西:


func UpdateText(text string) string {

    re, _ := regexp.Compile(`<img.*?src=\"(.*?)\"`)

    text = re.ReplaceAllStringFunc(text, updateImgSrc) 

    return text

}


// update "/m/1.jpg" to "/a/1.jpg" 

func updateImgSrc(imgSrcText, prefix string) string {

    // replace "m" by prefix

    return "<img src=\"" + newImgSrc + "\""

}

我检查了文档, ReplaceAllStringFunc 不支持参数,但是实现我的目标的最佳方法是什么?


更一般地说,我想找到一个模式的所有出现,然后用一个由源字符串+一个新参数组成的新字符串更新每个模式,有人能给出任何想法吗?


富国沪深
浏览 195回答 2
2回答

牧羊人nacy

我同意这些评论,你可能不想用正则表达式解析 HTML(坏事会发生)。但是,让我们假设它不是 HTML,并且您只想替换子匹配项。你可以这样做func UpdateText(input string) (string, error) {&nbsp; &nbsp; re, err := regexp.Compile(`img.*?src=\"(.*?)\.(.*?)\"`)&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; return "", err&nbsp; &nbsp; }&nbsp; &nbsp; indexes := re.FindAllStringSubmatchIndex(input, -1)&nbsp; &nbsp; output := input&nbsp; &nbsp; for _, match := range indexes {&nbsp; &nbsp; &nbsp; &nbsp; imgStart := match[2]&nbsp; &nbsp; &nbsp; &nbsp; imgEnd := match[3]&nbsp; &nbsp; &nbsp; &nbsp; newImgName := strings.Replace(input[imgStart:imgEnd], "m", "a", -1)&nbsp; &nbsp; &nbsp; &nbsp; output = output[:imgStart] + newImgName + input[imgEnd:]&nbsp; &nbsp; }&nbsp; &nbsp; return output, nil}(请注意,我稍微更改了您的正则表达式以分别匹配文件扩展名)

拉丁的传说

这是我使用 html 解析器的解决方案。func UpdateAllResourcePath(text, prefix string) (string, error) {&nbsp; &nbsp; doc, err := goquery.NewDocumentFromReader(strings.NewReader(text))&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; return "", err&nbsp; &nbsp; }&nbsp; &nbsp; sel := doc.Find("img")&nbsp; &nbsp; length := len(sel.Nodes)&nbsp; &nbsp; for index := 0; index < length; index++ {&nbsp; &nbsp; &nbsp; &nbsp; imgSrc, ok := sel.Eq(index).Attr("src")&nbsp; &nbsp; &nbsp; &nbsp; if !ok {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; continue&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; newImgSrc, err := UpdateResourcePath(imgSrc, prefix)&nbsp; &nbsp; // change the imgsrc here&nbsp; &nbsp; &nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return "", err&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; sel.Eq(index).SetAttr("src", newImgSrc)&nbsp; &nbsp; }&nbsp; &nbsp; newtext, err := doc.Find("body").Html()&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; return "", err&nbsp; &nbsp; }&nbsp; &nbsp; return newtext, nil}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go