如何在 Golang 中搜索和替换字符串中的文本?

go programmingserver side programmingprogramming

我们经常需要将某些字符串或所有符合特定模式的字符串替换为其他字符串。在 Golang 中,我们可以使用 Go 标准库 strings 包提供的原生函数,也可以自行编写逻辑。

在本文中,我们将看到不同的示例,其中我们将使用 strings 包中最常用的两个函数。这些函数是 −

  • strings.Replace()

  • strings.ReplaceAll()

我们先来看一下这些函数的签名,以便对它们有更深入的了解。

strings.Replace() 的语法

func Replace(s, old, new string, n int) string
  • 上述函数中的第一个参数是包含子字符串的字符串,我们希望将其与另一个字符串匹配以进行替换。

  • 第二个参数是我们希望用新字符串替换的子字符串。

  • 第三个参数是我们希望用来替换在字符串。

  • 最后一个参数是我们要替换的次数。

需要注意的是,如果我们想要替换所有与模式匹配的出现次数,那么在调用 Replace 函数时,我们应该传递 -1 作为最后一个参数。

让我们探索一个 Replace 函数的示例,以了解其工作原理。

示例 1

考虑下面的代码。

package main
import (
   "fmt"
   "strings"
)
func main() {
   var str string = "It is not is a string is"
   res := strings.Replace(str, "is", "isn't", 2)
   fmt.Println(res)
}

输出

如果我们在上述代码上运行命令 go run main.go,我们将在终端中得到以下输出。

It isn't not isn't a string is

请注意,我们只是替换了匹配字符串的前两次出现。如果我们想要替换所有出现的位置,可以使用下面的代码。

示例 2

考虑下面的代码。

package main
import (
   "fmt"
   "strings"
)
func main() {
   var str string = "It is not is a string is"
   res := strings.Replace(str, "is", "isn't", -1)
   fmt.Println(res)
}

输出

如果我们对上述代码运行命令 go run main.go,我们将在终端中得到以下输出。

It isn't not isn't a string isn't

strings.ReplaceAll() 函数的行为类似于 Replace(),但最后一个参数是 -1

示例 3

考虑下面的代码。

package main
import (
   "fmt"
   "strings"
)
func main() {
   var str string = "It is not is a string is"
   res := strings.ReplaceAll(str, "is", "isn't")
   fmt.Println(res)
}

输出

如果我们在上面的代码上运行命令go run main.go,那么我们将在终端中得到以下输出。

It isn't not isn't a string isn't

相关文章