正则表达式匹配字符串值并替换golang中的所有匹配项

时间:2018-08-22 10:37:21

标签: go

匹配字符串的正则表达式

%20

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

在Golang中

我需要替换其中的每个实例,可以有任意多个,并替换为

"{{skin url=\"wysiwyg/Out_story.png\"}} 从上方

1 个答案:

答案 0 :(得分:1)

({{(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上进行测试。

相关问题