Replace one occurrence with regexp

I cound't use accepted solution because my pattern was very complicated. I ended up with using ReplaceAllStringFunc : https://play.golang.org/p/ihtuIU-WEYG

package main

import (
    "fmt"
    "regexp"
)

var pat = regexp.MustCompile("bar(.)(x)")

func main() {
    src := "foobar1xfoobar2x"
    flag := false
    output := pat.ReplaceAllStringFunc(src, func(a string) string {
        if flag {
            return a
        }
        flag = true
        return pat.ReplaceAllString(a, "baz$1$2")
    })
    fmt.Println(output)
}

In general, if you use lazy match and use anchors for beginning and end, you can have the replace first behavior:

replace `^(.*?)bar(.*)$` with `$1baz$2`.

Example:

package main

import (
    "fmt"
    "regexp"
)

func main() {
    src := "foobar1xfoobar2x"
    pat := regexp.MustCompile("^(.*?)bar(.*)$")
        repl := "${1}baz$2"
    output := pat.ReplaceAllString(src, repl)
    fmt.Println(output)
}

Output

foobaz1xfoobar2x

I had the same problem. The most clean solution I've come up with:

package main

import (
    "fmt"
    "regexp"
    "strings"
)

func main() {
    re, _ := regexp.Compile("[a-z]{3}")
    s := "aaa bbb ccc"

    // Replace all strings
    fmt.Println(re.ReplaceAllString(s, "000"))

    // Replace one string
    found := re.FindString(s)
    if found != "" {
        fmt.Println(strings.Replace(s, found, "000", 1))
    }
}

Running:

$ go run test.go 
000 000 000
000 bbb ccc

Tags:

Regex

Go