Replace one occurrence with regular expression

I want to replace only one instance with a regex, not all. How can I do this using the Go regexp library?

input: foobar1xfoobar2x
regex: bar(.)x
replacement: baz$1

ReplaceAllString output: foobaz1foobaz2
ReplaceOneString output: foobaz1foobar2x

+7
source share
3 answers

In general, if you use a lazy match and use bindings to start and end, you can replace the 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 
+8
source

I did not use the decision made because my template was very complex. I ended up 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) } 
0
source

I have the same problem. The cleanest solution I came up with:

 package main import ( "fmt" "regexp" "strings" ) func main() { re, _ := regexp.Compile("[az]{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)) } } 

Run:

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

Source: https://habr.com/ru/post/945638/


All Articles