Go语言中使用正则校验需要用到 regexp 包
先介绍几种常用的方法:
1、 使用MatchString函数
regexp.MatchString(pattern string, s string) pattern为正则表达式,s为需要校验的字符传
例:
match,_:=regexp.MatchString("p([a-z]+)ch","peddach") 返回的第一个参数是bool类型即匹配结果,第二个参数是error类型
fmt.Println(match) //结果为true
2、使用 Compile函数或MustCompile函数
它们的区别是Compile返回两个参数*Regexp,error类型,而MustCompile只返回*Regexp类型
func Compile(expr string) (*Regexp, error) {}
func MustCompile(str string) *Regexp {}
它们的作用是将正则表达式进行编译,返回优化的 Regexp 结构体,该结构体有需多方法。
例
r,_:=regexp.Compile("p([a-z]+)ch")
b:=r.MatchString("peach")
fmt.Println(b) //结果为true
或
r1:=regexp.MustCompile("p([a-z]+)ch")
b1:r1.MatchString("peach")
fmt.Println(b) //结果为true