I have some strings in the following possible forms:
MYSTRING=${MYSTRING}\n
MYSTRING=\n
MYSTRING=randomstringwithvariablelength\n
I want to be able to regex this into MYSTRING=foo, basically replacing everything between MYSTRING= and \n. I've tried:
re := regexp.MustCompile("MYSTRING=*\n")
s = re.ReplaceAllString(s, "foo")
But it doesn't work. Any help is appreciated.
P.S. the \n is to indicate that there's a newline for this purpose. It's not actually there.
You may use
(MYSTRING=).*
and replace with ${1}foo. See the online Go regex demo.
Here, (MYSTRING=).* matches and captures MYSTRING= substring (the ${1} will reference this value from the replacement pattern) and .* will match and consume any 0+ chars other than line break chars up to the end of the line.
See the Go demo:
package main
import (
"fmt"
"regexp"
)
const sample = `MYSTRING=${MYSTRING}
MYSTRING=
MYSTRING=randomstringwithvariablelength
`
func main() {
var re = regexp.MustCompile(`(MYSTRING=).*`)
s := re.ReplaceAllString(sample, `${1}foo`)
fmt.Println(s)
}
Output:
MYSTRING=foo
MYSTRING=foo
MYSTRING=foo
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