regexp.Compile
package main

import (
	"fmt"
	"regexp"
)

func main() {
	reg, err := regexp.Compile("[a-z0-9#$%&]+")
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(reg.MatchString("AIh"))
	fmt.Println(reg.MatchString("an82&#"))
}

运行结果

false
true
AIhan82&#(re *Regexp) MatchString(s string) bool[a-z0-9#$%&]a-z0-9#$%&AIhha-za-z0-9[a-z0-9#$%&]++[a-z0-7#$%&]
reg, err := regexp.Compile("[a-z0-7#$%&]")
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(reg.MatchString("AI"))
	fmt.Println(reg.MatchString("an82&#"))
	fmt.Println(reg.MatchString("A!+"))
	fmt.Println(reg.MatchString("aA!+"))
	fmt.Println(reg.MatchString(strconv.Itoa(8)))
	fmt.Println(reg.MatchString(strconv.Itoa(789)))

结果

false
true
false
true
false
true
regexp.MustCompile
regexp.Compileerror
package main

import (
	"fmt"
	"regexp"
	"strconv"
)

func main() {
	s := "日本"
	s2 := "中国"
	s3 := "ad"
	s4 := "G"
	s5 := 9
	s6 := 708
	s7 := "@"
	s8 := "国8h+¥œ"
	s9 := "%"
	s10 := "^"
	ss := make([]string, 0)
	ss = append(ss, s, s2, s3, s4, strconv.Itoa(s5), strconv.Itoa(s6), s7, s8, s9, s10)
	reg := regexp.MustCompile("^[a-zA-Z0-8中国!@#&*+_¥œø]+$")
	for k, v := range ss {
		fmt.Println(k, v, reg.MatchString(v))
	}
}

运行结果

0 日本 false
1 中国 true
2 ad true
3 G true
4 9 false
5 708 true
6 @ true
7 国8h+¥œ true
8 % false
9 ^ false
Compile(expr string) (*Regexp, error)MustCompile(str string) *Regexp(re *Regexp) MatchString(s string) bool

匹配中文

"^[a-zA-Z0-9\u4e00-\u9fa5]{3,8}$"
package main

import (
	"fmt"
	"regexp"
)

func main() {
	reg, err := regexp.Compile("^[a-zA-Z0-9\u4e00-\u9fa5]{3,8}$")
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(reg.MatchString("春暖花开"))
	fmt.Println(reg.MatchString("春暖"))
	fmt.Println(reg.MatchString("568"))
	fmt.Println(reg.MatchString("aingege"))
	fmt.Println(reg.MatchString("EIOGNE"))
	fmt.Println(reg.MatchString("DIfin梅6"))
}

运行结果

true
false
true
true
true
true

注意:函数Compile和MustCompile传入参数时要写在英文双引号里面,不可以是单引号,也不可以是特殊字符 ` ,就是esc键底下那个键,在匹配中文时这个符号和\u不匹配,会报错。

package main

import (
	"fmt"
	"regexp"
)

func main() {
	//reg, err := regexp.Compile(`^[a-zA-Z0-9\u4e00-\u9fa5]{3,8}$`)
	reg := regexp.MustCompile(`^[a-zA-Z0-9\u4e00-\u9fa5]{3,8}$`)
	//reg := regexp.MustCompile("^[a-zA-Z0-9\u4e00-\u9fa5]{3,8}$")
	//reg, err := regexp.Compile("^[a-zA-Z0-9\u4e00-\u9fa5]{3,8}$")
	//if err != nil {
	//	fmt.Println(err)
	//}
	fmt.Println(reg.MatchString("春暖花开"))
	fmt.Println(reg.MatchString("春暖"))
	fmt.Println(reg.MatchString("569你$kfa"))
	fmt.Println(reg.MatchString("aingege"))
	fmt.Println(reg.MatchString("EIOGNE"))
	fmt.Println(reg.MatchString("DIfin梅6"))
}

运行结果

panic: regexp: Compile(`^[a-zA-Z0-9\u4e00-\u9fa5]{3,8}$`): error parsing regexp: invalid escape sequence: `\u`
````\u