英文:
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 := "%temp%"
strings.ReplaceAll(s, oldstr, newstr) // => "foo%temp%bar"
Try it on the Go Playground.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论