【问题标题】:Go: split string by comma but ignore comma within double quotesGo:用逗号分割字符串,但忽略双引号内的逗号
【发布时间】:2020-04-05 10:34:27
【问题描述】:

我输入了用逗号分隔的字符串。但它可能包含需要忽略的双引号内的逗号。下面是示例字符串

str := "\"age\": \"28\", \"favorite number\": \"26\", \"salary\": \"$1,234,108\""

下面是我用来分割逗号的代码,但它失败了,逗号是双引号中字符串的一部分。

s1 := strings.Split(s, "\"")
s2 := strings.Join(s1, "")
s3 := strings.Split(s2, ",")

所以任何想法如何解决这个问题。

【问题讨论】:

  • 您的输入字符串似乎是 JSON 内容的片段,这引出了您为什么不使用解析器的问题?
  • 是的,它更多的是 JSON 字符串,但冒号被替换为“\t”,因为某些字段可以有冒号。还要对被序列化为 JSON 字符串的字符串进行后处理。
  • 为那个特殊的奇怪格式写一个解析器。
  • Yes, its more of JSON string but colons are replaced with "\t" as some fields can have colon 让我怀疑给定的例子是否合法。
  • 您能否指定您希望从此输入字符串得到的结果。你想用逗号分割它,忽略字符串中的逗号吗?

标签: regex go


【解决方案1】:

下面的函数会做你想做的事。

// SplitAtCommas split s at commas, ignoring commas in strings.
func SplitAtCommas(s string) []string {
    res := []string{}
    var beg int
    var inString bool

    for i := 0; i < len(s); i++ {
        if s[i] == ',' && !inString {
            res = append(res, s[beg:i])
            beg = i+1
        } else if s[i] == '"' {
            if !inString {
                inString = true
            } else if i > 0 && s[i-1] != '\\' {
                inString = false
            }
        }
    }
    return append(res, s[beg:])
}

此处提供完整示例:https://play.golang.org/p/f5jceIm4nbE

【讨论】:

    【解决方案2】:

    您可以使用下面的代码来获取键和值

    package main
    
    import (
    
    "fmt"
    "strings"
    
    )
    
    func main() {
      str := "\"age\": \"28\", \"favorite number\": \"26\", \"salary\": \"$1,234,108\""
      arr := strings.Split(str,`",`)
      for _, v := range arr {
         val := strings.Split(v,`:`)
         fmt.Println("Key:",val[0],"value:",val[1])
      }
    }
    

    playground运行

    【讨论】:

    • 不,如果字符串包含:\",,这将出错
    • 是的,你完全正确。但他的问题只包括字符串中的逗号所以,我提出了这个解决方案,否则正则表达式将是一个更好的解决方案。
    猜你喜欢
    • 2012-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-23
    • 2011-12-25
    相关资源
    最近更新 更多