-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.go
47 lines (40 loc) · 993 Bytes
/
util.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package sapcontrol
import (
"regexp"
"strconv"
)
var (
// compiled regex should be global to compile it only once on start up
reParseValueUnit = regexp.MustCompile(`^(-|-?\d+(.\d+)?)( ([^ ]+))?$`)
)
// stringInSlice returns bool if given string is in given slice.
func stringInSlice(s string, slice []string) bool {
for _, e := range slice {
if e == s {
return true
}
}
return false
}
// ParseValueUnit returns value and unit from given string. If no value/unit pair could be parsed, returned unit equals given string.
func ParseValueUnit(s string) (interface{}, string) {
t := reParseValueUnit.FindStringSubmatch(s)
if len(t) == 0 {
return 0, s
}
// convert value "-" to "0"
if t[1] == "-" {
t[1] = "0"
}
// check conversion to int, it is mostly int ;)
var v interface{}
v, err := strconv.ParseInt(t[1], 10, 64)
if err != nil {
// check conversion to float
v, err = strconv.ParseFloat(t[1], 64)
if err != nil {
return 0, s
}
}
return v, t[4]
}