doushun1904 2018-01-25 18:01
浏览 1669
已采纳

删除Golang中的双引号或单引号

Shouldn't strconv.Unquote handle both single and double quotes?

See also https://golang.org/src/strconv/quote.go - line 350

However following code returns a syntax error:

s, err := strconv.Unquote(`'test'`)
if err != nil {
  fmt.Println(err)
} else {
  fmt.Println(s)
}

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

But double quotes work as expected:

s, err := strconv.Unquote(`"test"`)
if err != nil {
  fmt.Println(err)
} else {
  fmt.Println(s)
}

What am I missing?

  • 写回答

3条回答 默认 最新

  • doujingqu3030 2018-01-25 21:05
    关注

    There is no ready function for what you want in the standard library.

    What you presented works, but we can make it simpler (and likely more efficient):

    func trimQuotes(s string) string {
        if len(s) >= 2 {
            if c := s[len(s)-1]; s[0] == c && (c == '"' || c == '\'') {
                return s[1 : len(s)-1]
            }
        }
        return s
    }
    

    Testing it:

    fmt.Println(trimQuotes(`'test'`))
    fmt.Println(trimQuotes(`"test"`))
    fmt.Println(trimQuotes(`"'test`))
    

    Output (try it on the Go Playground):

    test
    test
    "'test
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?