Home > Back-end >  scanning a string separated by ":" in golang
scanning a string separated by ":" in golang

Time:09-17

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

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?

CodePudding user response:

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
}
  •  Tags:  
  • go
  • Related