result1 gfdsgf ------------------------------------------------------ str := "[a-z]" r := regexp.MustCompile(str) in := "fdsagsa" out := r.ReplaceAllStringFunc(in, strings.ToUpper) fmt.Println(string(out))
FDSAGSA
子匹配
FindAllStringSubmatch(s string, n int) [][]string
FindAllStringSubmatchIndex(s string, n int) [][]int
1 2 3 4 5 6 7 8 9
tempReg := "[\w-]+@([\w]+(?:\.[\w]+)+)" tempRegCom, err := regexp.Compile(tempReg) if err == nil{ matched := tempRegCom.FindAllStringSubmatch("abc@gmail.com",-1) for _, match := range matched { fmt.Printf("email is: %s, domain is: %s\n", match[0], match[1]) } } email is: abc@gmail.com, domain is: gmail.com
命名分组
命名分组就是给具有默认分组编号的组另外再给一个别名。命名分组的语法格式如下:
1
(?P<name>正则表达式)#name是一个合法的标识符
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
str := `Alice 20 alice@gmail.com` 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)
for i, name := range groupNames { if i != 0 && name != "" { // 第一个分组为空(也就是整个匹配) result[name] = match[i] } } fmt.Println(result)
[Alice 20 alice@gmail.com Alice 20 alice@gmail.com], [ name age email], 4, 4 map[name:Alice age:20 email:alice@gmail.com]