go-regex 电脑版发表于:2022/4/27 22:05 ```go package main import ( "fmt" "regexp" ) // 正则表达式 // 1. 匹配字符 // 2. 替换字符 // 3. 查找字符 // https://pkg.go.dev/regexp#section-documentation func main() { fmt.Println("1. 匹配字符") matchFun() fmt.Println("2. 查找字符") replaceFun() fmt.Println("3. 查找字符") compileFun() fmt.Println("4. 其他") compileOtherFun() } // 1. 匹配字符 func matchFun() { //目标源是字节 matched, err := regexp.Match("^abc.*z$", []byte("abcdefghwz")) fmt.Println(matched, err) //目标源是string matched, err = regexp.MatchString("^abc.*z$", "abcdedafgz") fmt.Println(matched, err) } func replaceFun() { re, _ := regexp.Compile("f([a-z]+)") fmt.Println("1. ", string(re.ReplaceAll([]byte("this is foo, that is func "), []byte("x")))) fmt.Println("2. ", string(re.ReplaceAllString("this is foo, that is func ", "x"))) } //查找字符 func compileFun() { re := regexp.MustCompile(".com") fmt.Println("1:" + re.FindString("www.baidu.com")) fmt.Println("2:" + re.FindString("www.wangyi.com")) fmt.Println("3:" + re.FindString("www.baidu.org")) } func compileOtherFun() { re, _ := regexp.Compile("f([a-z]+)") fmt.Println("1. ", re.Match([]byte("foo"))) fmt.Println("2. ", re.MatchString("foo")) //只匹配一次 fmt.Println("3. ", re.FindString("foo, func")) //返回查找到的所有索引 fmt.Println("4. ", re.FindStringIndex("foo, func")) //只匹配一次, 返回的结果中 , 索引为0的值 是整个匹配串的值, 第二个是子表达式的值,如果没有子表达式, 则不检测 fmt.Println("5. ", re.FindStringSubmatch("foo, func")) // n为-1的时候, 匹配所有符合条件的 字符串, n不为-1的时候表示匹配n次 fmt.Println("6. ", re.FindAllString("foo func fan ", -1)) fmt.Println("7. ", re.FindAllString("foo func fan ", 2)) } ```