How to split a string by multiple delimiters

前端 未结 5 1046
长发绾君心
长发绾君心 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:44

    You may use

    strings.FieldsFunc(input, Split)
    

    Try it on The Go Playground:

    package main
    
    import (
        "fmt"
        "strings"
    )
    
    func main() {
        input := `xxxxx:yyyyy:zzz.aaa.bbb.cc:dd:ee:ff`
        a := strings.FieldsFunc(input, Split)
        t := Target{a[0], a[1], a[2], a[3], a[4], a[5], a[6]}
        fmt.Println(t) // {xxxxx yyyyy zzz aaa bbb cc dd}
    }
    func Split(r rune) bool {
        return r == ':' || r == '.'
    }
    
    type Target struct {
        Service string
        Type    string
        Domain  string
        Plan    string
        Host    string
        Region  string
        Other   string
    }
    

    output:

    {xxxxx yyyyy zzz aaa bbb cc dd}
    

提交回复
热议问题