How to split a string by multiple delimiters

前端 未结 5 1113
长发绾君心
长发绾君心 2021-02-20 03:13

I want to parse a string xxxxx:yyyyy:zzz.aaa.bbb.cc:dd:ee:ff to a struct in Go, how can I do it with multiple delimiter \':\' and \'.\'.

Edit:

I want to split the

5条回答
  •  -上瘾入骨i
    2021-02-20 03:42

    Alright. This isn't a very elegant solution but it should at least get you started and works for the specific example you've given. In reality you'd probably want to add some error handling or generalize the logic a bit to work with a broader set of inputs.

    type Target struct {
        Service string
        Type string
        Domain string
        Plan string
        Host string
        Region string
        Other string
    }
    
    func main() {
        input := `xxxxx:yyyyy:zzz.aaa.bbb.cc:dd:ee:ff`
        t := Target{}
        tokens := strings.Split(input, ":")
        t.Service = tokens[0]
        t.Type = tokens[1]
        subtokens := strings.Split(tokens[2], ".")
        t.Domain = subtokens[0]
        t.Plan = subtokens[1]
        t.Host = subtokens[2]
        t.Region = subtokens[3]
        t.Other = tokens[3]
        fmt.Printf("%v", t)
    }
    

    Working example here; https://play.golang.org/p/57ZyOfdbvo

提交回复
热议问题