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