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条)

报告相同问题?

悬赏问题

  • ¥15 宇视监控服务器无法登录
  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥15 DruidDataSource一直closing
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥50 power BI 从Mysql服务器导入数据,但连接进去后显示表无数据