Search code examples
parsinggoformatted

Parse formatted string in Golang


I'm trying to parse a GNSS RINEX file using Golang.

For example, here's the RINEX specification for the VERSION line:

+--------------------+------------------------------------------+------------+
|RINEX VERSION / TYPE| - Format version (2.11)                  | F9.2,11X,  |
|                    | - File type ('O' for Observation Data)   |   A1,19X,  |
|                    | - Satellite System: blank or 'G': GPS    |   A1,19X   |
|                    |                     'R': GLONASS         |            |
|                    |                     'S': Geostationary   |            |
|                    |                          signal payload  |            |
|                    |                     'E': Galileo         |            |
|                    |                     'M': Mixed           |            |
+--------------------+------------------------------------------+------------+

Each line in a RINEX file has a fixed width of 80 ASCII characters + "\n". In this example the first 9 characters represent the version number (float).

In Python I might use:

struct.unpack("9s11s1s19s1s19s20s", line)

which would return a tuple with 7 strings.

I'm new to go and have been trying to use fmt.Sscanf for reading formatted text:

func main() {
    str := "     2.11           OBSERVATION DATA    G (GPS)             RINEX VERSION / TYPE\n"
    var value float32
    a, err := fmt.Sscanf(str,"%9.2f", &value)
    fmt.Println(a)
    fmt.Println(err)
    fmt.Println(value)
}

returns:

0
bad verb %. for float32
0

Is there any package in go that permits parsing of fixed width data?

And if not, what might be a good approach for writing something similar to Python's struct?


Solution

  • For example,

    package main
    
    import (
        "errors"
        "fmt"
        "strconv"
        "strings"
    )
    
    // http://gage14.upc.es/gLAB/HTML/LaunchHTML.html
    // http://gage14.upc.es/gLAB/HTML/Observation_Rinex_v2.11.html
    
    func parseVersionType(line string) (version float64, fileType, satellite, label string, err error) {
        label = line[60:80]
        if label != "RINEX VERSION / TYPE" {
            err = errors.New("Unknown header label")
            return
        }
        version, err = strconv.ParseFloat(strings.TrimSpace(line[0:9]), 64)
        if err != nil {
            return
        }
        fileType = line[20:21]
        satellite = line[40:41]
        return
    }
    
    func main() {
        line := "     2.11           OBSERVATION DATA    G (GPS)             RINEX VERSION / TYPE\n"
        version, fileType, satellite, label, err := parseVersionType(line)
        fmt.Printf("%g %q %q %q %v\n", version, fileType, satellite, label, err)
    }
    

    Output:

    2.11 "O" "G" "RINEX VERSION / TYPE" <nil>