1 回答

TA貢獻1852條經驗 獲得超7個贊
您可以使用正則表達式使用單個表達式捕獲這兩個值。FindStringSubmatch:
func NewObjectSizeFromString(input_str string) (*ObjectSize, error) {
var defaultReturn *ObjectSize = nil
full_search_pattern := `^([0-9]+)([KMGT]?B)$`
rg, err := regexp.Compile(full_search_pattern)
if err != nil {
return defaultReturn, errors.New("Could not compile search expression")
}
matched := rg.FindStringSubmatch(input_str)
if matched == nil {
return defaultReturn, errors.New("Not in valid format")
}
i, err := strconv.ParseInt(matched[1], 10, 32)
return &ObjectSize{int(i), SizeUnit(matched[2])}, nil
}
正則表達式匹配^([0-9]+)([KMGT]?B)$
^
- 字符串的開頭([0-9]+)
- 組 1(此值將保存在):一個或多個數字matched[1]
([KMGT]?B)
- 組 2 (它將在): 一個可選的 , , , 字母, 然后是一個字母matched[2]
K
M
G
T
B
$
- 字符串末尾。
請注意,這將保持整個比賽。matched[0]
- 1 回答
- 0 關注
- 94 瀏覽
添加回答
舉報