Go:用逗号分割字符串,但忽略双引号内的逗号

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

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

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

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

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


MMTTMM
浏览 118回答 2
2回答

largeQ

以下功能将执行您想要的操作。// SplitAtCommas split s at commas, ignoring commas in strings.func SplitAtCommas(s string) []string {&nbsp; &nbsp; res := []string{}&nbsp; &nbsp; var beg int&nbsp; &nbsp; var inString bool&nbsp; &nbsp; for i := 0; i < len(s); i++ {&nbsp; &nbsp; &nbsp; &nbsp; if s[i] == ',' && !inString {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; res = append(res, s[beg:i])&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; beg = i+1&nbsp; &nbsp; &nbsp; &nbsp; } else if s[i] == '"' {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if !inString {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; inString = true&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; } else if i > 0 && s[i-1] != '\\' {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; inString = false&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return append(res, s[beg:])}完整的示例可以在这里找到: https: //play.golang.org/p/f5jceIm4nbE。

肥皂起泡泡

您可以使用下面的代码来获取键和值package mainimport ("fmt""strings")func main() {&nbsp; str := "\"age\": \"28\", \"favorite number\": \"26\", \"salary\": \"$1,234,108\""&nbsp; arr := strings.Split(str,`",`)&nbsp; for _, v := range arr {&nbsp; &nbsp; &nbsp;val := strings.Split(v,`:`)&nbsp; &nbsp; &nbsp;fmt.Println("Key:",val[0],"value:",val[1])&nbsp; }}在操场上奔跑
打开App,查看更多内容
随时随地看视频慕课网APP