}

Go: How to search and replace text using golang?

Created:

Introduction

We continue with our series of Go programming lenguage tutorials. This time we are going to search en replace in Strings using Go. To solve this problem we will use the package strings.

We are going to cover some useful examples.

First example: replace all occurrences of a word in a string

In our first example we will use the Replace function. The Replace function has three arguments, the first is the string to search for, the second is the replacement and the last argument refers to the numbers of times to do the replace.

Here is the function arguments, if n < 0 it will replace all occurrences.

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

Now our example code to replace a word in string using go:

package main

import (
    "fmt"
    "strings"
)

func main() {
    bookPart := "Because of its wonderful formation this mountain was of abundant interest to all during their brief halt, but it was examined most carefully by the three young soldiers who were to be stationed on its crest. The mountain was full of soldiers."
    bookPart = strings.Replace(bookPart, "mountain", "hill", -1)
    fmt.Println(bookPart)
}

Our code below will replace all occurences of "mountain" with "hill". If you only want to replace the first occurrence just call replace with "1" as third argument:

strings.Replace(bookPart, "mountain", "hill", -1)

As in most of lenguage if you need to search or replace special char use "\" to escape them.

Using Replacer

The Replacer is a class in the strings package. The class will allow you to ombine many replacements.

Replacer needs pairs of strings, those pair corresponds to all the replacements that you need to do in the string. Once you have a replacer instance, you call Replace with the string where you need to do the replacement.

package main

import (
    "fmt"
    "strings"
)

func main() {
    numbers := "one, one, two, three, four, four, four, five"

    replacer := strings.NewReplacer("one", "ten",
            "two", "twelve",
            "three", "thirdteen")

    result := replacer.Replace(numbers)
    fmt.Println(result)
}