如何用单引号转义字符串

时间:2021-01-09 05:41:45

标签: go unicode-string unicode-escapes

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

'\'"Hello,\nworld!\r\n\u1F60ANice to meet you!\nFirst Name\tJohn\nLast Name\tDoe\n'

应该变成

'"Hello,
world!
?Nice to meet you!
First Name      John
Last Name       Doe

我该如何实现?

strconv.Unquote 不适用于 \n 换行符(https://github.com/golang/go/issues/15893https://golang.org/pkg/strconv/#Unquote),并且简单地 strings.ReplaceAll(ing 支持所有 Unicode 代码会很痛苦点和其他反斜杠代码,如 \n & \r & \t

我可能要求太多了,但是如果它像 strconv.Unquote 可能能够做/正在做的那样自动验证 Unicode 会很好(它知道 x Unicode 代码点可能成为一个字符) ,因为我可以用 unicode/utf8.ValidString 做同样的事情。

1 个答案:

答案 0 :(得分:0)

@CeriseLimón 提出了这个答案,我只是将它放入一个带有更多恶作剧的函数中以支持 \n。首先,这会交换 '",并将 \n 更改为实际的换行符。然后它strconv.Unquote每行,因为strconv.Unquote无法处理换行符,然后重新交换'"并将它们拼凑在一起。

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])
}
相关问题