Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang regex replace between strings

Tags:

regex

go

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.

like image 629
bli00 Avatar asked Dec 14 '25 04:12

bli00


1 Answers

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
like image 97
Wiktor Stribiżew Avatar answered Dec 15 '25 18:12

Wiktor Stribiżew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!