Go 如何用单引号转义字符串

Go 如何用单引号转义字符串,go,unicode-string,unicode-escapes,Go,Unicode String,Unicode Escapes,我试图在Go中取消引用使用单引号的字符串(语法与Go字符串文字语法相同,但使用单引号而不是双引号): 应该成为 '"Hello, world! @CeriseLimón came up with this answer, and I just put it into a function with more shenanigans to support \ns. First, this swaps ' and ", and changes \ns to actual newl

我试图在Go中取消引用使用单引号的字符串(语法与Go字符串文字语法相同,但使用单引号而不是双引号):

应该成为

'"Hello,
world!
@CeriseLimón came up with this answer, and I just put it into a function with more shenanigans to support 
\n
s. First, this swaps
'
and
"
, and changes
\n
s to actual newlines. Then it
strconv.Unquote
s each line, since
strconv.Unquote
cannot handle newlines, and then reswaps
'
and
"
and pieces them together.

func unquote(s string) string {
        replaced := strings.NewReplacer(
            `'`,
            `"`,
            `"`,
            `'`,
            `\n`,
            "\n",
        ).Replace(s[1:len(s)-1])
        unquoted := ""
        for _, line := range strings.Split(replaced, "\n") {
            tmp, err := strconv.Unquote(`"` + line + `"`)
            repr.Println(line, tmp, err)
            if err != nil {
                return nil, NewInvalidAST(obj.In.Text.LexerInfo, "*Obj.In.Text.Text")
            }
            unquoted += tmp + "\n"
        }
        return strings.NewReplacer(
            `"`,
            `'`,
            `'`,
            `"`,
        ).Replace(unquoted[:len(unquoted)-1])
}
“你好, 世界!
@CeriseLimón提出了这个答案,我只是把它放在一个有更多诡计的函数中,以支持
\n
s。首先,这个函数交换
'
,并将
\n
s更改为实际的换行符。然后,它将
strconv.Unquote
s每一行,因为
strconv.Unquote
无法处理换行符,然后将
重新交换并将它们分割在一起


我不熟悉Go,但是你能用JSON解析器反序列化它吗?谢谢,@Matthew!它有效:Go或JSON中不使用单引号作为字符串分隔符。编辑问题以说明使用的语法。是来自Javascript、Vimscript吗?问题中的示例使用单引号。你链接的文章使用反引号。哪一个是字符串不是一段符文。如果语法是Go语法,用
替换为
,则使用
strconv.Unquote(strings.ReplaceAll(s,“”,“\”)
。此外,编辑问题以说明语法。字符串是字节序列,而不是字节片段。
'"Hello,
world!
@CeriseLimón came up with this answer, and I just put it into a function with more shenanigans to support 
\n
s. First, this swaps
'
and
"
, and changes
\n
s to actual newlines. Then it
strconv.Unquote
s each line, since
strconv.Unquote
cannot handle newlines, and then reswaps
'
and
"
and pieces them together.

func unquote(s string) string {
        replaced := strings.NewReplacer(
            `'`,
            `"`,
            `"`,
            `'`,
            `\n`,
            "\n",
        ).Replace(s[1:len(s)-1])
        unquoted := ""
        for _, line := range strings.Split(replaced, "\n") {
            tmp, err := strconv.Unquote(`"` + line + `"`)
            repr.Println(line, tmp, err)
            if err != nil {
                return nil, NewInvalidAST(obj.In.Text.LexerInfo, "*Obj.In.Text.Text")
            }
            unquoted += tmp + "\n"
        }
        return strings.NewReplacer(
            `"`,
            `'`,
            `'`,
            `"`,
        ).Replace(unquoted[:len(unquoted)-1])
}