Search & Replace in Strings

One common task when working with text in code, is searching and replacing inside strings. 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
package main

import (
    "fmt"
    "strings"
)

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

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

In this example, we replace all occurrences of “Gopher” with “Go”. 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.

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”.