Golang 如何搜索和替换一个字符串中的文本

Golang 如何搜索和替换一个字符串中的文本

我们经常想用一些其他的字符串来替换某些字符串或所有符合模式的字符串。为了在 Golang 中做到这一点,我们可以使用Go标准库中的 字符串 包为我们提供的本地函数,或者我们可以自己编写相同的逻辑。

在这篇文章中,我们将看到不同的例子,其中我们将使用 字符串 包中两个最常用的函数。这两个函数是 –

  • strings.Replace( )

  • strings. ReplaceAll( )

让我们首先考虑一下这些函数的签名,以便对它们有更多了解。

strings.Replace()的语法

func Replace(s, old, new string, n int) string
Go
  • 上述函数的第一个参数是包含一个子串的字符串,我们想用另一个字符串进行匹配替换。

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

  • 第三个参数是我们想用它来替换字符串中被匹配的模式的字符串。

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

应该注意的是,如果我们想替换所有与模式匹配的出现,那么我们在调用 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

输出

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

It isn't not isn't a string is
Go

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

例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

输出

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

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

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

输出

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

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

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册