正则表达式匹配字符串值并替换golang中的所有引用
匹配字符串的正则表达式是什么正则表达式匹配字符串值并替换golang中的所有引用,go,Go,匹配字符串的正则表达式是什么 "{{media url=\"wysiwyg/Out_story.png\"}} 或 在戈兰 我需要替换每一个实例,可以有任意数量的实例,并用 https://img.abc.com/xyz/valueOfURL 从上面看{media| skin url=\\\.\\\}应该完成这项工作 它还允许您在代码中以字符串形式获取媒体或皮肤类型,以便在需要时进一步使用 例如,此代码: package main import "fmt" import "regexp"
"{{media url=\"wysiwyg/Out_story.png\"}}
或
在戈兰
我需要替换每一个实例,可以有任意数量的实例,并用
https://img.abc.com/xyz/valueOfURL 从上面看{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
您可以在或上自己测试。您尝试过什么?你遇到了什么问题?这是我发布之前遇到的:{{media url=.*.}那么问题出在哪里?谢谢。我需要补充一下吗?之后,否则一切都完了。用附加值替换它怎么样?我需要替换这些的每一个实例,可以有任意数量的实例,并替换为from Abi如果你想替换它,你需要的是使用字符串。我将用整个字符串更新答案:……我最初放的示例也捕获了双引号,现在已修复,它应该完全按照您的要求执行。不过,下一次在这里提问时,请至少包含一段您尝试编写的代码,我们将指导您如何使其工作,而不是为您编写代码:p
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