golang split string by multiple delimitters

1,896 views
Skip to first unread message

Sankar

unread,
Jul 17, 2012, 6:12:33 AM7/17/12
to golan...@googlegroups.com
Hi,

I have a string "hello <format> world" and I need to split it based on multiple characters "<> ". How do I get this ? The strings.Fields splits only by space. strings.Split too doesn't work. I saw that FieldsFunc whose documentation looks like it might solve this. But I am not able to understand it as there are no examples. Also, the helper text is a bit confusing to me and I am not able to understand it clearly.

Can someone help me with the code for understanding how to split by multiple delimitters ? It may be good, if you can also get this added to the FieldsFunc API as an example code.

Thanks.

Sankar

peterGo

unread,
Jul 17, 2012, 6:40:06 AM7/17/12
to golan...@googlegroups.com
Sankar,

Here's an example,

package main

import (
    "fmt"
    "strings"
)

func bracket(r rune) bool {
    return r == '<' || r == '>'
}

func main() {
    s := "hello <format> world"
    fmt.Println("s:", s)
    t := strings.FieldsFunc(s, bracket)
    fmt.Println("t:", len(t), t)
}

Output:
s: hello <format> world
t: 3 [hello  format  world]

Peter

Sankar

unread,
Jul 17, 2012, 8:37:39 AM7/17/12
to golan...@googlegroups.com
Perfect. Thank you a lot. This whole rune thing confused me. Now after seeing your code, if I look at the documentation, it is clear to me :) 

Please add this as an example code to the documentation, if possible.

Thanks.
Reply all
Reply to author
Forward
0 new messages