Search code examples
regexgosubstringre2

How to extract substrings


I wrote in Go the following code to extract two values ​​inside the string.

I used two regexp to seek the numbers (float64).

The first result is the correct, only de number. But the second is wrong.

This is the code:

package main

import (
    "fmt"
    "regexp"
)

func main() {

    // RegExp utiliza la sintaxis RE2
    pat1 := regexp.MustCompile(`[^m2!3d][\d\.-]+`)
    s1 := pat1.FindString(`Torre+Eiffel!8m2!3d-48.8583701!4d-2.2944813!3m4!1s0x47e66e2964e34e2d:0x8ddca9ee380ef7e0!8m2!3d-48.8583701!4d-2.2944813`)

    pat2 := regexp.MustCompile(`[^!4d][\d\.-]+`)
    s2 := pat2.FindString(`Torre+Eiffel!8m2!3d-48.8583701!4d-2.2944813!3m4!1s0x47e66e2964e34e2d:0x8ddca9ee380ef7e0!8m2!3d-48.8583701!4d-2.2944813`)

    fmt.Println(s1) // Print -> -48.8583701 
    fmt.Println(s2) // Print -> m2  (The correct answer is "-2.2944813")
}

Here I modify the syntax

pat2 := regexp.MustCompile(!4d[\d\.-]+)

and I get the following answer:

    !4d-2.2944813

but it's not what I'm expecting.


Solution

  • It seems like you are only interessed in the latitude and longitute of an attraction and not really in the regex.

    Maybe you just use something like this:

    package main
    
    import (
        "fmt"
        "strconv"
        "strings"
    )
    
    var replacer = strings.NewReplacer("3d-", "", "4d-", "")
    
    func main() {
        var str = `Torre+Eiffel!8m2!3d-48.8583701!4d-2.2944813!3m4!1s0x47e66e2964e34e2d:0x8ddca9ee380ef7e0!8m2!3d-48.8583701!4d-2.2944813`
        fmt.Println(getLatLong(str))
    }
    
    func getLatLong(str string) (float64, float64, error) {
        parts := strings.Split(str, "!")
        if latFloat, err := strconv.ParseFloat(replacer.Replace(parts[2]), 64); err != nil {
            return 0, 0, err
        } else if lngFloat, err := strconv.ParseFloat(replacer.Replace(parts[3]), 64); err != nil {
            return 0, 0, err
        } else {
            return latFloat, lngFloat, nil
        }
    }
    

    https://play.golang.org/p/UOIwGbl6nrb