Golang:转义单引号

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

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, "'", "\\'")

https://play.golang.org/p/BPtU2r8dXrs

答案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)

https://go.dev/play/p/6IFecrHmN3z

huangapple
  • 本文由 发表于 2015年10月16日 20:30:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/33170566.html
匿名

发表评论

匿名网友

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

确定