英文:
Golang : Escaping single quotes
问题
在Go语言中,可以通过使用反斜杠来转义单引号。以下是你提供的代码的修改版本:
str := "I'm Bob, and I'm 25."
str = strings.Replace(str, "'", "\\'", -1)
这样修改后,str的值将会是:
"I\'m Bob, and I\'m 25."
这样就成功地转义了单引号。
英文:
Is there a way to escape single quotes in go?
The following:
str := "I'm Bob, and I'm 25."
str = strings.Replace(str, "'", "\'", -1)
Gives the error: unknown escape sequence: '
I would like str to be
"I\'m Bob, and I\'m 25."
答案1
得分: 33
你需要在 strings.Replace 中也转义斜杠。
str := "I'm Bob, and I'm 25."
str = strings.ReplaceAll(str, "'", "\\'")
https://play.golang.org/p/BPtU2r8dXrs
英文:
You need to ALSO escape the slash in strings.Replace.
str := "I'm Bob, and I'm 25."
str = strings.ReplaceAll(str, "'", "\\'")
答案2
得分: 13
你可以将替换的字符串用反引号括起来:
strings.ReplaceAll(str, "'", `\'`)
英文:
+to @KeylorSanchez answer: your can wrap replace string in back-ticks:
strings.ReplaceAll(str, "'", `\'`)
答案3
得分: 1
// addslashes()
func Addslashes(str string) string {
var buf bytes.Buffer
for _, char := range str {
switch char {
case ''':
buf.WriteRune('\')
}
buf.WriteRune(char)
}
return buf.String()
}
如果你想转义单引号/双引号或反斜杠,你可以参考 https://github.com/syyongx/php2go
英文:
// addslashes()
func Addslashes(str string) string {
var buf bytes.Buffer
for _, char := range str {
switch char {
case '\'':
buf.WriteRune('\\')
}
buf.WriteRune(char)
}
return buf.String()
}
If you want to escaping single/double quotes or backlash, you can refer to https://github.com/syyongx/php2go
答案4
得分: 0
strings.Replacer
可以一次性转义多个不同的字符。如果你想在不同的地方重用相同的逻辑,这也很方便。
quoteEscaper := strings.NewReplacer(`'`, `\'`, `"`, `\"`)
str := `They call me "Bob", and I'm 25.`
str = quoteEscaper.Replace(str)
https://go.dev/play/p/6IFecrHmN3z
英文:
strings.Replacer
can be used to escape a number of different characters at once. Also handy if you want to reuse the same logic in different places.
quoteEscaper := strings.NewReplacer(`'`, `\'`, `"`, `\"`)
str := `They call me "Bob", and I'm 25.`
str = quoteEscaper.Replace(str)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论