Parse text

suggest change

Using fmt.Sscanf

fmt.Sscanf is the reverse of fmt.Sprintf. Given a string and formatting directive you can parse 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 formatting string doesn't match parsed string, fmt.Sscanf returns an error. In our examples the error is EOF because we wanted to extract more values than were in the string.

Using strings.Split

string.Split allows to split a string by a separator.

s := "this,. is,. a,. string"
a := strings.Split(s, ",.")
fmt.Printf("a: %#v\n", a)
a: []string{"this", " is", " a", " string"}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents