-1

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.

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Jumanyi
  • 375
  • 1
  • 2
  • 9

2 Answers2

1

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

tobi.g
  • 924
  • 6
  • 23
0

You where almost there. Try (?m)(?:3d|4d)-([\d\.-]+)(?:!|$)

https://regex101.com/r/8KgirB/1

All you need is a matching group around the [\d\.-]+ part. With this group you are able to access it directly

package main

import (
    "fmt"
    "regexp"
)

func main() {
    var re = regexp.MustCompile(`(?m)(?:3d|4d)-([\d\.-]+)!`)
    var str = `Torre+Eiffel!8m2!3d-48.8583701!4d-2.2944813!3m4!1s0x47e66e2964e34e2d:0x8ddca9ee380ef7e0!8m2!3d-48.8583701!4d-2.2944813`

    for _, match := range re.FindAllStringSubmatch(str, -1) {
        fmt.Println(match[1])
    }
}
tobi.g
  • 924
  • 6
  • 23
  • Thank you very much. While you answered, I found part of the solution and published it. For the first value, it works with `[^ m2! 3d] [\ d \ .-] +`, but not for the second. – Jumanyi Jul 27 '20 at 22:05