golang 正则之命名分组

5 min read

示例:

str := `Alice 20 [email protected]`

// 使用命名分组,显得更清晰
re := regexp.MustCompile(`(?P<name>[a-zA-Z]+)\s+(?P<age>\d+)\s+(?P<email>\w+@\w+(?:\.\w+)+)`)
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)

// 转换为map
for i, name := range groupNames {
    if i != 0 && name != "" { // 第一个分组为空(也就是整个匹配)
        result[name] = match[i]
    }
}

prettyResult, _ := json.MarshalIndent(result, "", "  ")

fmt.Printf("%s\n", prettyResult)

输出为:

[Alice 20 [email protected] Alice 20 [email protected]], [ name age email], 4, 4
{
  "age": "20",
  "email": "[email protected]",
  "name": "Alice"
}