ReplaceAllString. Sometimes we have a string that can be matched with a Regexp pattern, and we want to replace each match with another string. This can be done with ReplaceAllString.
ReplaceAllString is similar to other Go regexp methods, but it adds the replacement step after the matching step. We call MustCompile before using ReplaceAllString().
Example. Here we show that we can replace strings using a pattern with regexp. This is some sample code from a Go program that generates this website.
Info We want to replace a string pattern starting with the word "stage" with a string ending with the word "compress."
Result We use the meta code $1 to reference the captured group after the word "stage," and place it in the result of ReplaceAllString.
package main
import (
"fmt""regexp"
)
func main() {
// Input string.
input := "/programs/stage-perls/"// Change a string starting with "stage" into a string ending with "compress."
re := regexp.MustCompile(`stage-([a-z]*)`)
replacementResult := re.ReplaceAllString(input, "stage-$1-compress")
// Before and after.
fmt.Println(input)
fmt.Println(replacementResult)
}/programs/stage-perls/
/programs/stage-perls-compress/
ReplaceAllStringFunc. In some situations, we may want to have a way to test each match before deciding on its replacement. We can use ReplaceAllStringFunc for these cases.
Info This program matches all non-word characters, and replaces them by evaluating the ReplaceExample() function.
Result The program changes the exclamation mark to a period, and changes all other matches to an underscore.
package main
import (
"fmt""regexp"
)
func ReplaceExample(a string) string {
// Change some strings that are matched.
if a == "!" {
return "."
}
return "_"
}
func main() {
text := "hello, friends!"
result := regexp.MustCompile(`\W`).ReplaceAllStringFunc(text, ReplaceExample)
fmt.Println(result)
}hello__friends.
Summary. With ReplaceAllString we have a way to perform more complex substring replacements. We can use patterns and even functions to determine what to replace and the replacement values.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Jan 10, 2025 (edit).