Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sscanf of multiple string fields in golang

Tags:

go

I am trying to use sscanf to parse multiple string fields. Here is an example code snippet:

package main

import "fmt"

func main() {
        var name, currency string

    _, err := fmt.Sscanf("transaction benson: dollars", "transaction %s: %s", &name, &currency)

    fmt.Println(err, name, currency)
}

The output is

input does not match format benson: 

Program exited.
like image 434
Ben Nelson Avatar asked Aug 23 '15 18:08

Ben Nelson


1 Answers

%s is greedy and gobbles up to the next space, which means it eats up the colon. After processing the %s, it then tries to scan in the colon, but wait, that’s already been consumed, and the next character is actually a space, not a colon! So it fails.

In C you’d get around this by using %[^:] rather than %s, but it appears Go doesn’t support this. You might need to find some way to parse your string without Sscanf.

like image 127
icktoofay Avatar answered Oct 13 '22 10:10

icktoofay