Parse text
suggest changeUsing fmt.Sscanf
fmt.Sscanf is the reverse of fmt.Sprintf. Given a string and a format, you can parse the string into components.
// extract int and float from a string
s := "48 123.45"
var f float64
var i int
nParsed, err := fmt.Sscanf(s, "%d %f", &i, &f)
if err != nil {
log.Fatalf("first fmt.Sscanf failed with %s\n", err)
}
fmt.Printf("i: %d, f: %f, extracted %d values\n", i, f, nParsed)
var i2 int
_, err = fmt.Sscanf(s, "%d %f %d", &i, &f, &i2)
if err != nil {
fmt.Printf("second fmt.Sscanf failed with %s\n", err)
}
i: 48, f: 123.450000, extracted 2 values
second fmt.Sscanf failed with EOF
fmt.Sscanf supports the same formatting directives as fmt.Sprintf.
If the format string asks for more values than the parsed string contains, fmt.Sscanf returns an error. In our example the error is EOF.
Using strings.Split
strings.Split splits a string around a separator.
s := "this,. is,. a,. string"
a := strings.Split(s, ",.")
fmt.Printf("a: %#v\n", a)
a: []string{"this", " is", " a", " string"}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents