在golang中替换反斜杠

huangapple go评论78阅读模式
英文:

Replacing backslashes in golang

问题

我们可以如何在Golang中替换反斜杠,类似于Python中的操作:

// Golang implementation
package main

import (
	"fmt"
	"strings"
)

func main() {
	regexp := `\\\\`
	cleanedRegexp := strings.ReplaceAll(regexp, `\\`, `%temp%`)
	cleanedRegexp = strings.ReplaceAll(cleanedRegexp, `%temp%`, `\`)
	fmt.Println(cleanedRegexp)
}

在Golang中,我们可以使用strings.ReplaceAll函数来替换字符串中的子字符串。在上面的示例中,我们首先将两个反斜杠替换为%temp%,然后再将%temp%替换为单个反斜杠。最后,我们打印出替换后的字符串cleanedRegexp

希望对你有所帮助!

英文:

How can we replace back slashes in golang something similar to we do in python:

# python implementation
cleaned_regexp = regexp.replace('\\\\', '%temp%').replace('\\\\', '\\')

Transitioning from python to golang and very recently started with development in go so any help will be really great.

Thanks

答案1

得分: 1

根据评论者的指示,由于包含两个反斜杠字符的字符串不需要特殊匹配,因此无需使用正则表达式。更简单的方法是使用strings.ReplaceAll()

还要注意,使用原始字符串字面值(用反引号括起来)可以使代码更容易理解,因为它避免了对反斜杠的解释。

s := `foo\\bar`
oldstr := `\\`
newstr := "%temp%"
strings.ReplaceAll(s, oldstr, newstr) // => "foo%temp%bar"

Go Playground上试一试。

英文:

As noted by commenters, there is no need to use a regular expression since the string containing two backslash characters requires no special matching. A simpler approach would be to use strings.ReplaceAll().

Note also that using a raw string literal (between back quotes) makes the code a bit easier to understand since it avoids interpreting the backslash.

<!-- language: lang-go -->

s := `foo\\bar`
oldstr := `\\`
newstr := &quot;%temp%&quot;
strings.ReplaceAll(s, oldstr, newstr) // =&gt; &quot;foo%temp%bar&quot;

Try it on the Go Playground.

huangapple
  • 本文由 发表于 2022年8月5日 20:06:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/73249507.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定