[Go] 在golang中使用正则表达式捕获子表达式

正则匹配并且可以捕获到()这个里面的子表达式的值,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

猜你喜欢

转载自www.cnblogs.com/taoshihan/p/11954172.html