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.com或playground上自行測試。
- 1 回答
- 0 關注
- 165 瀏覽
添加回答
舉報