Search & Replace All in Strings

One common task when working with text in code, is searching and replacing inside strings. For example you might want to replace X with Y. Or equally, you might want to replace Z with nothing, removing it. In this blog post, we’ll explore two ways to perform a search and replace operation in Go using the strings and regexp packages.

Strings Package

The strings package provides a simple method called Replace() for search and replace operations. This method has the following signature:

1
func Replace(s, old, new string, n int) string

Here’s an example of how to use the Replace method:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
package main

import (
    "fmt"
    "strings"
)

func main() {
    text := "Welcome to GopherCoding!"
    newText := strings.Replace(text, "Gopher", "Kitty", -1)

    // or strings.ReplaceAll(text, "Gopher", "Kitty")

    fmt.Println(newText) // Output: Welcome to KittyCoding!
}

In this example, we replace all occurrences of “Gopher” with “Kitty”. The -1 as the last argument indicates that all occurrences should be replaced. If you want to limit the number of replacements, change the value to the desired number. Another way to do this is to use the ReplaceAll function.

Example In Action

search and replace in a string

Regexp Package

For more complex search and replace operations, the regexp package offers powerful regular expression functionality. The ReplaceAllString method allows you to search and replace substrings using regular expressions:

1
func (re *Regexp) ReplaceAllString(src, repl string) string

Here’s an example using the ReplaceAllString function:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
package main

import (
    "fmt"
    "regexp"
)

func main() {
    text := "Welcome to GopherCoding!"
    re := regexp.MustCompile("Gopher")
    newText := re.ReplaceAllString(text, "Go")

    fmt.Println(newText) // Welcome to GoCoding!
}

In this example, we create a regular expression object with the MustCompile function and use the ReplaceAllString method to replace all occurrences of “Gopher” with “Go”.