How to split a string by multiple delimiters

前端 未结 5 1114
长发绾君心
长发绾君心 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条回答
  •  一向
    一向 (楼主)
    2021-02-20 03:32

    You can use this function, which can split a string by multiple runes:

    import "fmt"
    import "strings"
    
    func SplitAny(s string, seps string) []string {
        splitter := func(r rune) bool {
            return strings.ContainsRune(seps, r)
        }
        return strings.FieldsFunc(s, splitter)
    }
    
    func main() {
        words := SplitAny("xxxxx:yyyyy:zzz.aaa.bbb.cc:dd:ee:ff", ".:")
        fmt.Println(strings.Join(words, " "))
    }
    

    Output:

    xxxxx yyyyy zzz aaa bbb cc dd ee ff
    

    Or even with one line of code:

    words := strings.FieldsFunc(s, func(r rune) bool { return strings.ContainsRune(" .:", r) })
    

提交回复
热议问题