Replacing Text
ReplaceAll patterns.
Pattern-Based Replacement
Regexps can rewrite text, not just find it. ReplaceAllString swaps every match with a replacement string.
package main
import (
"fmt"
"regexp"
)
func main() {
re := regexp.MustCompile("[0-9]+")
fmt.Println(re.ReplaceAllString("a1b2c3", "#"))
}Replacing Whole Words
A pattern like cat|dog lets you replace several alternatives in one pass.
package main
import (
"fmt"
"regexp"
)
func main() {
re := regexp.MustCompile("cat|dog")
fmt.Println(re.ReplaceAllString("my cat and dog", "pet"))
}All lessons in this course
- regexp Basics
- Finding and Extracting
- Replacing Text
- Performance Tips