[Go] 在golang中使用正则表达式捕获子表达式
- 作者: 我的逗比中带着高冷
- 来源: 51数据库
- 2021-08-23
正则匹配并且可以捕获到()这个里面的子表达式的值,linux的grep命令没办法捕获子表达式的值,只能获取到整条正则匹配的内容
package main import "regexp" import "fmt" func main() { str := `(.*?)(\d+)(.*?)\d(.*)\d` r := regexp.mustcompile(str) matchs := r.findstringsubmatch("tao123shi5han567") for _, s := range matchs { fmt.println(s) } }
上面的正则中验证了.*是贪婪 .*?是非贪婪 ,下面匹配的字符串切片第一条是整条数据,后面的每一个对应正则括号里捕获的内容
tao@tao-pc:/var/www/html/go-project/test$ go run test.go
tao123shi5han567
tao
123
shi
han56
推荐阅读