I want to replace a only one instance with a regex rather than all of them. How would I do this with Go's regexp
library?
input: foobar1xfoobar2x
regex: bar(.)x
replacement: baz$1
ReplaceAllString
output: foobaz1foobaz2
ReplaceOneString
output: foobaz1foobar2x
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
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With