How to Replace with Regex in Go

Use regexp.MustCompile and ReplaceAllString to find patterns and replace them in Go strings.

Use the regexp package's ReplaceAllString function to replace all matches of a pattern with a replacement string. Compile the pattern once, then call ReplaceAllString on your target string.

package main

import (
	"fmt"
	"regexp"
)

func main() {
	pattern := regexp.MustCompile(`\d+`)
	text := "Room 101, Floor 2"
	result := pattern.ReplaceAllString(text, "X")
	fmt.Println(result) // Output: Room X, Floor X
}