Home > Software design >  How to improve a split logic in golang
How to improve a split logic in golang

Time:12-07

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.

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)
        }

    }

}

CodePudding user response:

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

  • Related