Golang 正则表达式

栏目: Go · 发布时间: 6年前

//MatchString返回的第一个参数是bool类型即匹配结果,第二个参数是error类型
sourceStr := `my email is gerrylon@163.com`
matched, _ := regexp.MatchString(`[\w-]+@[\w]+(?:\.[\w]+)+`, sourceStr)
fmt.Printf("%v", matched) // true

r,_:=regexp.Compile("p([a-z]+)ch")
b:=r.MatchString("peach")
fmt.Println(b)  //结果为true

//Compile函数或MustCompile函数是将正则表达式进行编译,返回优化的 Regexp 结构体
//区别是Compile返回两个参数*Regexp,error类型,而MustCompile只返回*Regexp类型
r1:=regexp.MustCompile("p([a-z]+)ch")
b1:=r1.MatchString("peach")
fmt.Println(b)   //结果为true

r,_:=regexp.Compile("p([a-z]+)ch")
fmt.Println(r.MatchString("peach"))  //j结果:true

//查找匹配的字符串
fmt.Println(r.FindString("peach punch"))  //打印结果:peach

//查找匹配字符串开始和结束位置的索引,而不是匹配内容[0 5]
fmt.Println(r.FindStringIndex("peach punch"))  //打印结果: [0 5]

//返回完全匹配和局部匹配的字符串,例如,这里会返回  p([a-z]+)ch 和 `([a-z]+) 的信息
fmt.Println(r.FindStringSubmatch("peach punch"))   //打印结果:[peach ea]

var sourceStr string = `
test text     lljflsdfjdskal
gerrylon@163.com
abc@gmail.com
someone@sina.com.cn`

re := regexp.MustCompile(`[\w-]+@([\w]+(?:\.[\w]+)+)`)
matched := re.FindAllStringSubmatch(sourceStr, -1)
for _, match := range matched {
    fmt.Printf("email is: %s, domain is: %s\n", match[0], match[1])
}
//email is: gerrylon@163.com, domain is: 163.com 
//email is: abc@gmail.com, domain is: gmail.com 
//email is: someone@sina.com.cn, domain is: sina.com.cn

//返回完全匹配和局部匹配的索引位置
fmt.Println(r.FindStringSubmatchIndex("peach punch"))   //打印结果: [0 5 1 3]

//返回所有的匹配项,而不仅仅是首次匹配项。正整数用来限制匹配次数
fmt.Println(r.FindAllString("peach punch pinch",-1))  //打印结果:[peach punch pinch]
fmt.Println(r.FindAllString("peach punch pinch",2)) //匹配两次   打印结果:[peach punch]

//返回所有的完全匹配和局部匹配的索引位置
fmt.Println(r.FindAllStringSubmatchIndex("peach punch pinch",-1)) 
//打印结果: [[0 5 1 3] [6 11 7 9] [12 17 13 15]]

//上面的例子中,我们使用了字符串作为参数,并使用了如 MatchString 这样的方法。
//我们也可以提供 []byte参数并将 String 从函数命中去掉。
fmt.Println(r.Match([]byte("peach")))    //打印结果:true

r1:=regexp.MustCompile("p([a-z]+)ch")

//将匹配的结果,替换成新输入的结果
fmt.Println(r1.ReplaceAllString("a peach","<fruit>"))     //打印结果: a <fruit>

//Func 变量允许传递匹配内容到一个给定的函数中,
in:=[]byte("a peach")
out:=r1.ReplaceAllFunc(in,bytes.ToUpper)
fmt.Printf(string(out)) //打印结果:   a PEACH

以上所述就是小编给大家介绍的《Golang 正则表达式》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Design for Hackers

Design for Hackers

David Kadavy / Wiley / 2011-10-18 / USD 39.99

Discover the techniques behind beautiful design?by deconstructing designs to understand them The term ?hacker? has been redefined to consist of anyone who has an insatiable curiosity as to how thin......一起来看看 《Design for Hackers》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

随机密码生成器
随机密码生成器

多种字符组合密码

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器