go笔记:正则表达式 ## 简单使用 如果要使用go语言的正则进行匹配,则需要先compile一个正则对象。这个对象是可复用的: ```go reNews, err := regexp.Compile("^([0-9]*).html") result := reNews.FindAllStringSubmatch(inputStr, -1) // 如果匹配 if k == 0 && len(result) > 0 { newsID := result[0][1] log.Info("TestRouter1 news id is %s", newsID) } ``` 就是这么简单。蛤。 ## group命名参数 使用命名参数: ```go func GetAllSub(re *regexp.Regexp, inputStr string) ([]map[string]string, error) { matches := re.FindAllStringSubmatch(inputStr, -1) groupNames := re.SubexpNames() ret := make([]map[string]string, 0) for _, match := range matches { tpRet := make(map[string]string) for i, groupName := range groupNames { if groupName == "" { continue } if i >= len(match) { return nil, fmt.Errorf("groupName:%v, index:%v,%v not found", groupName, i, match) } tpRet[groupName] = match[i] } ret = append(ret, tpRet) } return ret, nil } re := regexp.MustCompile(`type\s+(?P[a-z0-9A-Z]*)\s+struct\s*{|type\s+(?P[a-z0-9A-Z]+)\s+interface\s*{`) ret, err := GetAllSub(re, `type hello struct{ } type world interface{ }`) log.Printf("groupNames:%v %v\n", ret, err) // [{"itName":"","strName":"hello"},{"itName":"world","strName":""}] ``` 来自 大脸猫 写于 2017-09-07 10:35 -- 更新于2021-01-11 13:13 -- 0 条评论