0PricingLogin
Go Academy · Lesson

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

  1. regexp Basics
  2. Finding and Extracting
  3. Replacing Text
  4. Performance Tips
← Back to Go Academy