package main import ( "fmt" "regexp" ) func main() { context1 := "3.14 123123 .68 haha 1.0 abc 6.66 123." //MustCompile解析并返回一个正则表达式。如果成功返回,该Regexp就可用于匹配文本。 //解析失败时会产生panic // d 匹配数字[0-9],d+ 重复>=1次匹配d,越多越好(优先重复匹配d) exp1 := regexp.MustCompile(`d+.d+`) //返回保管正则表达式所有不重叠的匹配结果的[]string切片。如果没有匹配到,会返回nil。 //result1 := exp1.FindAllString(context1, -1) //[3.14 1.0 6.66] result1 := exp1.FindAllStringSubmatch(context1, -1) //[[3.14] [1.0] [6.66]] fmt.Printf("%v ", result1) fmt.Printf(" ------------------------------------ ") context2 := ` <title>标题</title> <div>你过来啊</div> <div>hello mike</div> <div>你大爷</div> <body>呵呵</body> ` //(.*?)被括起来的表达式作为分组 //匹配<div>xxx</div>模式的所有子串 exp2 := regexp.MustCompile(`<div>(.*?)</div>`) result2 := exp2.FindAllStringSubmatch(context2, -1) //[[<div>你过来啊</div> 你过来啊] [<div>hello mike</div> hello mike] [<div>你大爷</div> 你大爷]] fmt.Printf("%v ", result2) fmt.Printf(" ------------------------------------ ") context3 := ` <title>标题</title> <div>你过来啊</div> <div>hello mike go</div> <div>你大爷</div> <body>呵呵</body> ` exp3 := regexp.MustCompile(`<div>(.*?)</div>`) result3 := exp3.FindAllStringSubmatch(context3, -1) //[[<div>你过来啊</div> 你过来啊] [<div>你大爷</div> 你大爷]] fmt.Printf("%v ", result3) fmt.Printf(" ------------------------------------ ") context4 := ` <title>标题</title> <div>你过来啊</div> <div>hello mike go</div> <div>你大爷</div> <body>呵呵</body> ` exp4 := regexp.MustCompile(`<div>(?s:(.*?))</div>`) result4 := exp4.FindAllStringSubmatch(context4, -1) /* [[<div>你过来啊</div> 你过来啊] [<div>hello mike go</div> hello mike go] [<div>你大爷</div> 你大爷]] */ fmt.Printf("%v ", result4) fmt.Printf(" ------------------------------------ ") for _, text := range result4 { fmt.Println(text[0]) //带有div fmt.Println(text[1]) //不带带有div fmt.Println("================ ") } }
https://blog.csdn.net/tennysonsky/article/details/79081524