Home
Go
regexp.ReplaceAllString Example
This page was last reviewed on Sep 23, 2024.
Dot Net Perls
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().
regexp.MatchString
regexp.Find
regexp.Split
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.
func
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 tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Sep 23, 2024 (new).
Home
Changes
© 2007-2024 Sam Allen.