ds1379551
ds1379551
2019-02-20 21:55
浏览 501
已采纳

Golang正则表达式替换字符串之间

I have some strings in the following possible forms:

MYSTRING=${MYSTRING}

MYSTRING=

MYSTRING=randomstringwithvariablelength

I want to be able to regex this into MYSTRING=foo, basically replacing everything between MYSTRING= and . I've tried:

re := regexp.MustCompile("MYSTRING=*
")
s = re.ReplaceAllString(s, "foo")

But it doesn't work. Any help is appreciated.


P.S. the is to indicate that there's a newline for this purpose. It's not actually there.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dsla94915
    dsla94915 2019-02-20 21:58
    已采纳

    You may use

    (MYSTRING=).*
    

    and replace with ${1}foo. See the online Go regex demo.

    Here, (MYSTRING=).* matches and captures MYSTRING= substring (the ${1} will reference this value from the replacement pattern) and .* will match and consume any 0+ chars other than line break chars up to the end of the line.

    See the Go demo:

    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)
    }
    

    Output:

    MYSTRING=foo
    MYSTRING=foo
    MYSTRING=foo
    
    点赞 评论

相关推荐