I'm, trying to split a certain string type to its constituents using Golang's regex.
What I have is a Sprinf(".2f", n)
of any given float (to simplify it to 2 decimal places), and would wish to separate the hundredths digit like:
"1.25" = ["1.2", "5"]
"1.99" = ["1.9", "9"]
In PHP, this is something like:
preg_match('/^ (\-? \d [.] \d) (\d) $/x', sprintf('%1.2f', $input), $matches)
and I can get the parts via $matches[0] and $matches[1].
Tried it with :
re := regexp.MustCompile(`/^ (\-? \d [.] \d) (\d) $/x`)
fmt.Printf("%q
", re.FindAllStringSubmatch("1.50", 2))
to no avail. Thanks in advance.
Why do you need regexp for this? Simply slice the string:
func split(s string) []string {
if len(s) == 0 {
return nil
}
return []string{s[:len(s)-1], s[len(s)-1:]}
}
Testing it:
nums := []string{
fmt.Sprintf("%.2f", 1.25),
fmt.Sprintf("%.2f", 1.99),
fmt.Sprintf("%.2f", 1.25),
fmt.Sprintf("%.2f", 1.2),
fmt.Sprintf("%.2f", 0.0),
fmt.Sprintf("%.2f", -1.2),
"",
}
for _, n := range nums {
fmt.Printf("%q = %q
", n, split(n))
}
Output (try it on the Go Playground):
"1.25" = ["1.2" "5"]
"1.99" = ["1.9" "9"]
"1.25" = ["1.2" "5"]
"1.20" = ["1.2" "0"]
"0.00" = ["0.0" "0"]
"-1.20" = ["-1.2" "0"]
"" = []