Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

scanning a string separated by ":" in golang

I need to string scan 23.584950:58.353603:an address, str:a place, name
into :

type Origin struct {
    Lat     float64 `json:"lat" binding:"required"`
    Lng     float64 `json:"lng" binding:"required"`
    Address string  `json:"address" binding:"required"`
    Name    string  `json:"name" binding:"required"`
}

My code:

package main

import "fmt"

type Origin struct {
    Lat     float64 `json:"lat" binding:"required"`
    Lng     float64 `json:"lng" binding:"required"`
    Address string  `json:"address" binding:"required"`
    Name    string  `json:"name" binding:"required"`
}

func (o *Origin) ParseString(str string) error {
    if str == "" {
        return nil
    }
    _, err := fmt.Sscanf(str, "%f:%f:%[^:]:%[^/n]", &o.Lat, &o.Lng, &o.Address, &o.Name)
    if err != nil {
        return fmt.Errorf("parsing origin: %s, input:%s", err.Error(), str)
    }
    return nil
}
func main() {
    o := &Origin{}
    o.ParseString("23.584950:58.353603:address, text:place, name, text")
    fmt.Println(o)
}

https://go.dev/play/p/uUTNyx2cDFB

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

However, struct o prints out: &{23.58495 58.353603 }. Address and name are not scanned properly. What is the correct format to be used in Sscanf to parse this string correctly?

>Solution :

You are using a regex to capture input, while using fmt.Scanff. fmt.Scanff does not support RegEx. If you want to use regex, use the regexp package.

Or you could use a simple strings.Split and parse the input to the correct type:

func (o *Origin) ParseString2(str string) error {
    if str == "" {
        return nil
    }
    parts := strings.Split(str, ":")
    if len(parts) != 4 {
        return errors.New("expected format '...:...:...:...")
    }

    f, err := strconv.ParseFloat(parts[0], 64)
    if err != nil {
        return err
    }
    o.Lat = f

    f, err = strconv.ParseFloat(parts[1], 64)
    if err != nil {
        return err
    }
    o.Lng = f
    o.Address = parts[2]
    o.Name = parts[3]

    return nil
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading