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

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.

图片转代码服务由CSDN问答提供 功能建议

我有以下形式的一些字符串:

   MYSTRING = $ {MYSTRING} 
 
MYSTRING = 
 
MYSTRING =具有可变长度的随机字符串
 
   
 
 

我希望能够将此表达式正则表达式化为 MYSTRING = foo ,基本上替换了 MYSTRING = 之间的所有内容。 我尝试过:

  re:= regexp.MustCompile(“ MYSTRING = * 
”)
s = re.ReplaceAllString(s,“ foo”)
 <  / code>  
 
 

,但是它不起作用。 感谢您的任何帮助。


P.S。 表示为此目的有一个换行符。 它实际上不在那里。

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

1条回答 默认 最新

  • 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
    
    已采纳该答案
    打赏 评论

相关推荐 更多相似问题