3

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.

2
  • So, 3 lines with MYSTRING=foo is expected here? Commented Feb 20, 2019 at 21:58
  • Yes. Basically I want to replace everything between MYSTRING= and \n with a string of my choice. Commented Feb 20, 2019 at 21:58

1 Answer 1

5

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.