猿问

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

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


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

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


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

s2 := strings.Join(s1, "")

s3 := strings.Split(s2, ",")

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


繁花如伊
浏览 503回答 2
2回答

阿波罗的战车

以下功能将执行您想要的操作。// 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

相关分类

Go
我要回答