bli00
bli00

Reputation: 2787

Golang regex replace between strings

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.

Upvotes: 3

Views: 1144

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626893

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

Upvotes: 5

Related Questions