Golang 正则表达式

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

//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 正则表达式》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

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

遗传算法

遗传算法

王小平 / 西安交通大学出版社 / 2002-1 / 40.00元

《遗传算法:理论应用与软件实现》全面系统地介绍了遗传算法的基本理论,重点介绍了遗传算法的经典应用和国内外的新发展。全书共分11章。第1章概述了遗传算法的产生与发展、基本思想、基本操作以及应用情况;第2章介绍了基本遗传算法;第3章论述了遗传算法的数学基础;第4章分析了遗传算法的多种改进方法;第5章初步介绍了进化计算理论体系;第6章介绍了遗传算法应用于数值优化问题;第7章介绍了遗传算法应用于组合优化问......一起来看看 《遗传算法》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试