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

How to improve a split logic in golang

Having the following examples as possibles values from an index:

values := [5]string{"32.5ms", "32.5 ms", "32.5%", "32.5 %", "none"}

note that the original values could be with spaces, or without spaces from the measure unit (32.5%,32.5 %, 32.5 %,etc)

I need to split the float value and the unit of measure (%, ms, etc) from the original value, the bellow code, do the result I want, but I wanna know if there is some way more clean to do this same logic, maybe without regex.

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

package main

import (
    "fmt"
    "regexp"
    "strings"
)

func main() {

    regexFloatNumbers := regexp.MustCompile(`[-]?\d[\d,]*[\.]?[\d{2}]*`)

    values := [5]string{"32.5ms", "32.5 ms", "32.5%", "32.5 %", "none"}

    for _, value := range values {

        if regexFloatNumbers.MatchString(value) {
            floatValue := regexFloatNumbers.FindString(value)
            fmt.Printf("ORIGINAL VALUE: %q\n", value)
            fmt.Printf("UNIT: %q\n", strings.TrimSpace(regexFloatNumbers.Split(value, -1)[1]))
            fmt.Printf("FLOAT VALUE: %v\n\n", floatValue)
        } else {
            fmt.Printf("float value for %v has not being found!", value)
        }

    }

}

>Solution :

Regular expressions seem like the right fit here. Personally I’d use subgroups for this, like so (I also cleaned up your regex a little which had some unnecessary syntax and what looks like a typo with [\d{2}]*):

regexFloatNumbers := regexp.MustCompile(`(-?\d[\d,]*\.?\d*) *(.*)`)

// ...

floatValue := regexFloatNumbers.FindStringSubmatch(value)
fmt.Printf("ORIGINAL VALUE: %q\n", value)
fmt.Printf("UNIT: %q\n", floatValue[1])
fmt.Printf("FLOAT VALUE: %v\n\n", floatValue[2])

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

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