To replace all occurrences of a substring in a string using regular expression in Go, you can use the Regexp.ReplaceAllString
function.
In this example,
str
.str
with "Hi" using Regexp.ReplaceAllString
function.package main
import (
"fmt"
"regexp"
)
func main() {
str := "Hello World Hello"
re := regexp.MustCompile("Hello")
newStr := re.ReplaceAllString(str, "Hi")
fmt.Println(newStr)
}
Hi World Hi
In this example,
str
.str
with 'Y' using Regexp.ReplaceAllString
function.package main
import (
"fmt"
"regexp"
)
func main() {
str := "Hello123World789"
re := regexp.MustCompile("\\d")
newStr := re.ReplaceAllString(str, "Y")
fmt.Println(newStr)
}
HelloYYYWorldYYY
In this tutorial, we learned How to Replace a Substring in a String using Regular Expression in Go language with well detailed examples.