duanhao5038 2019-02-26 23:27
浏览 1569
已采纳

Golang正则表达式匹配并替换某个字符串后的第一个匹配项

Following up on my previous question about using Golang's regex to replace between strings. I now have a bit of complexity added to it. Here is what the contexts of my file looks like:

foo:
    blahblah
    MYSTRING=*
bar:
    blah
    blah
    MYSTRING=*

I need to replace what's between MYSTRING= and with a string of my choice (like previous stated in the original post). I can do that with:

var re = regexp.MustCompile(`(MYSTRING=).*`)
s := re.ReplaceAllString(content, `${1}stringofmychoice`)

But now I need to match and replace only after a certain occurrence. So that the contents of my file can look something like this:

foo:
    blahblah
    MYSTRING=foostring
bar:
    blah
    blah
    MYSTRING=barstring

ReplaceAllString obviously replaces everything, which is not what I want. Is there a way to only match and replace the first occurrence after a certain string?


For a bit of background about all of this. I'm trying to write a program to edit the contents of a given docker-compose.yml file and its environment variables. I need to edit the environment variable MYSTRING differently depending on what service it's listed under. In the example above, the two different services would be foo and bar.

  • 写回答

1条回答 默认 最新

  • dta25920 2019-02-26 23:52
    关注

    You may use ReplaceAllStringFunc and use a regex like

    (?m)^bar:(?:
    \s{4}.*)+
    

    See the regex demo. It will match a bar block indented with four whitespaces. Then, after a match is obtained, you may use a regular ReplaceAllString on the match.

    See the Go demo:

    package main
    
    import (
        "fmt"
        "regexp"
    )
    
    const sample = `foo:
        blahblah
        MYSTRING=*
    bar:
        blah
        blah
        MYSTRING=*`
    
    func main() {
        re := regexp.MustCompile(`(?m)^bar:(?:
    \s{4}.*)+`)
        re_2 := regexp.MustCompile(`(MYSTRING=).*`)
        s := re.ReplaceAllStringFunc(sample, func(m string) string {
                    return re_2.ReplaceAllString(m, `${1}stringofmychoice`)
            })
        fmt.Println(s)
    }
    

    Here, the second occurrence is changed in the bar block:

    foo:
        blahblah
        MYSTRING=*
    bar:
        blah
        blah
        MYSTRING=stringofmychoice
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效