有沒有辦法在go中轉義單引號?下列:str := "I'm Bob, and I'm 25."str = strings.Replace(str, "'", "\'", -1)給出錯誤:未知轉義序列:'我希望 str 成為"I\'m Bob, and I\'m 25."
3 回答

絕地無雙
TA貢獻1946條經驗 獲得超4個贊
您還需要轉義strings.Replace 中的斜線。
str := "I'm Bob, and I'm 25."
str = strings.ReplaceAll(str, "'", "\\'")
https://play.golang.org/p/BPtU2r8dXrs

一只萌萌小番薯
TA貢獻1795條經驗 獲得超7個贊
// 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
- 3 回答
- 0 關注
- 402 瀏覽
添加回答
舉報
0/150
提交
取消