Golang正则表达式替换字符串

the*_*may 3 regex go

我有以下可能形式的字符串:

MYSTRING=${MYSTRING}\n
MYSTRING=\n
MYSTRING=randomstringwithvariablelength\n
Run Code Online (Sandbox Code Playgroud)

我希望能够以正则表达式到这一点MYSTRING=foo,基本上之间的一切替换MYSTRING=\n.我试过了:

re := regexp.MustCompile("MYSTRING=*\n")
s = re.ReplaceAllString(s, "foo")
Run Code Online (Sandbox Code Playgroud)

但它不起作用.任何帮助表示赞赏.


PS \n表示为此目的有换行符.它实际上并不存在.

Wik*_*żew 5

你可以用

(MYSTRING=).*
Run Code Online (Sandbox Code Playgroud)

并替换为${1}foo.请参阅在线Go regex演示.

在这里,(MYSTRING=).*匹配并捕获MYSTRING=substring(${1}将从替换模式引用此值)并.*匹配并使用除了换行符之外的任何0+字符,直到行的末尾.

参见Go演示:

package main

import (
    "fmt"
    "regexp"
)

const sample = `MYSTRING=${MYSTRING}
MYSTRING=
MYSTRING=randomstringwithvariablelength
`
func main() {
    var re = regexp.MustCompile(`(MYSTRING=).*`)
    s := re.ReplaceAllString(sample, `${1}foo`)
    fmt.Println(s)
}
Run Code Online (Sandbox Code Playgroud)

输出:

MYSTRING=foo
MYSTRING=foo
MYSTRING=foo
Run Code Online (Sandbox Code Playgroud)