golang之正则校验

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值