import (
"encoding/json"
"fmt"
"regexp"
)
str := `9x_xx:995:88` // `9x_xx:995`
// 使用命名分组,一次匹配多个值
re := regexp.MustCompile(`(?P<fname>\w+):+(?P<mod>[1-9]*):*(?P<strlen>[0-9]*)`)
match := re.FindStringSubmatch(str)
groupNames := re.SubexpNames()
fmt.Printf("%v, %v, %d, %d\n", match, groupNames, len(match), len(groupNames))
result := make(map[string]string)
if len(match) == len(groupNames) {
// 转换为map
for i, name := range groupNames {
if i != 0 && name != "" { // 第一个分组为空(也就是整个匹配)
result[name] = match[i]
}
}
}
prettyResult, _ := json.MarshalIndent(result, "", " ")
fmt.Printf("%s\n", prettyResult)