【问题标题】:How to escape a string with single quotes如何用单引号转义字符串
【发布时间】:2021-04-14 19:03:56
【问题描述】:

我正在尝试取消引用 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 做同样的事情。

【问题讨论】:

  • 我不熟悉 Go,但你能用 JSON 解析器反序列化它吗?
  • 谢谢,@Matthew!它有效:play.golang.org/p/Q6cy-anCwds
  • 单引号不用作 Go 或 JSON 中的字符串分隔符。编辑问题以说明使用的语法。是来自 Javascript、Vimscript、???
  • 问题中的示例使用单引号。您链接的文章使用反引号。它是哪一个?字符串不是符文片。
  • 如果语法是 Go 语法,将 " 替换为 ',则使用 strconv.Unquote(strings.ReplaceAll(s, "'", "\""))。此外,编辑问题以说明语法。字符串是字节序列,而不是字节片。

标签: go unicode-string unicode-escapes


【解决方案1】:

@CeriseLimón 想出了这个答案,我只是把它放到一个有更多恶作剧的函数中来支持\ns。首先,这交换了'",并将\ns 更改为实际的换行符。然后它strconv.Unquotes 每行,因为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])
}

【讨论】:

    猜你喜欢
    • 2023-04-02
    • 2023-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-30
    相关资源
    最近更新 更多