亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

正則表達式匹配字符串值并替換 golang 中的所有匹配項

正則表達式匹配字符串值并替換 golang 中的所有匹配項

Go
MYYA 2023-03-21 17:11:05
匹配字符串的正則表達式是什么"{{media url=\"wysiwyg/Out_story.png\"}}或者"{{skin url=\"wysiwyg/Out_story.png\"}}在戈蘭我需要替換這些的每個實例,它們可以有任意數量并將其替換為https://img.abc.com/xyz/valueOfURL從上面
查看完整描述

1 回答

?
有只小跳蛙

TA貢獻1824條經驗 獲得超8個贊

({{(media|skin) url=\\"(.*)\\"}})應該做的工作。


它還將允許您在代碼中將類型(媒體或皮膚)作為字符串獲取,以便在需要時進一步使用。


例如,這段代碼:


package main


import "fmt"

import "regexp"


func main() {


    re := regexp.MustCompile(`{{(media|skin) url=.*}}`)

    stringMedia := "{{media url=\"wysiwyg/Out_story.png\"}}"

    stringSkin := "{{skin url=\"wysiwyg/Out_story.png\"}}"


    match := re.FindStringSubmatch(stringMedia)

    if len(match) != 0 {

        fmt.Printf("1. %s\n", match[1])

    }


    match = re.FindStringSubmatch(stringSkin)

    if len(match) != 0 {

        fmt.Printf("2. %s\n", match[1])

    }

}

產出


1. media

2. skin

然后,要用它包含的 URL 替換匹配項,您可以這樣做(注意對 regexp 的調整以獨立捕獲完整匹配項和 url):


package main


import (

    "fmt"

    "regexp"

    "strings"

)


func main() {


    re := regexp.MustCompile(`({{(media|skin) url=\\"(.*)\\"}})`)

    stringMedia := "other stuff {{media url=\"wysiwyg/Out_story.png\"}} other stuff"

    stringSkin := "other stuff {{skin url=\"wysiwyg/Out_story.png\"}} other stuff"


    match := re.FindStringSubmatch(stringMedia)

    if len(match) != 0 {

        stringMedia = strings.Replace(stringMedia, match[1], fmt.Sprintf("https://img.abc.com/xyz/%s", match[3]), -1)

        fmt.Println(stringMedia)

    }


    match = re.FindStringSubmatch(stringSkin)

    if len(match) != 0 {

        stringSkin = strings.Replace(stringSkin, match[1], fmt.Sprintf("https://img.abc.com/xyz/%s", match[3]), -1)

        fmt.Println(stringSkin)

    }

}

輸出:


other stuff https://img.abc.com/xyz/wysiwyg/Out_story.png other stuff

other stuff https://img.abc.com/xyz/wysiwyg/Out_story.png other stuff

您可以在regex-golang.appspot.complayground上自行測試。



查看完整回答
反對 回復 2023-03-21
  • 1 回答
  • 0 關注
  • 165 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號