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()
.
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.
string
pattern starting with the word "stage" with a string
ending with the word "compress."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.
ReplaceExample()
function.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.
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.