Replace text in strings
suggest changeReplace 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'
The last argument of strings.Replace is the maximum number of replacements. -1 means replace all. strings.ReplaceAll is the same call with that count.
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 replace text with a regular expression. (?U)or.*al is a non-greedy ((?U) flag) expression that matches original.
We replace all parts of the string matching the regex with a string replaced.
The expression is non-greedy, so it matches the shortest string. The default is greedy and matches the longest string.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents