Essential Go Strings  Suggest an edit

Replace strings

Replace string with strings.Replace

s := "original string original"
s2 := strings.Replace(s, "original", "replaced", -1)
fmt.Printf("s2: '%s'\n", s2)
s2: 'replaced string replaced'

Last argument in strings.Replace is max number of replacements. -1 means "replace all".

Replace string with a regular expression

s := "original string original"
rx := regexp.MustCompile("(?U)or.*al")
s2 := rx.ReplaceAllString(s, "replaced")
fmt.Printf("s2: '%s'\n", s2)
s2: 'replaced string replaced'

This shows how to do strings replacements with regular expressions. (?U)or.*al is a non-greedy ((?U) flag) regular expression that matches original string.

We replace all parts of the string matching the regex with a string replaced.

Regular expression is non-greedy, meaning it matches the shortest possible string as opposed to default greedy match which looks for longest possible match.

  ↑ ↓ to navigate     ↵ to select     Esc to close