go语言与正则表达式
-
编译解析正则表达式
func MustCompile(str string) *Regexp
- 参数:正则表达式字符串。推荐使用反引号`
- 返回值:编译后,go语言能够识别出来的一个正则表达式结构体
-
利用正则从字符串中提取有用信息
func (re *Regexp) FindAllStringSubmatch(s string, n int) [][]string
- 参数1:需要过滤的字符串
- 参数2:匹配次数
- 返回值:利用正则表达式匹配成功的子串
- 匹配项中的行、列
- 列0带有参考项
- 列1不带参考项
Demo
func main() {
str := "abc a7c mfc cat 8ca azc cba"
// 编译解析正则
ret := regexp.MustCompile(`a.c`)
// 筛选有用信息
data := ret.FindAllStringSubmatch(str, -1) // -1 表示有几次匹配几次
fmt.Println(data)
}
// [[abc] [a7c] [azc]]
上面的data是一个字符切片类型,data[i][0]表示带有匹配参考项的数据,data[i][1]表示不带有匹配参考项的数据,例如:
func main() {
str := `<!DOCTYPE html>
<html lang="zh-CN">
<head>
<title>Go语言标准库文档中文版 | Go语言中文网 | Golang中文社区 | Golang中国</title>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=no">
<meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1">
<meta charset="utf-8">
<link rel="shortcut icon" href="/static/img/go.ico">
<link rel="apple-touch-icon" type="image/png" href="/static/img/logo2.png">
<meta name="author" content="polaris <polaris@studygolang.com>">
<meta name="keywords" content="中文, 文档, 标准库, Go语言,Golang,Go社区,Go中文社区,Golang中文社区,Go语言社区,Go语言学习,学习Go语言,Go语言学习园地,Golang 中国,Golang中国,Golang China, Go语言论坛, Go语言中文网">
<meta name="description" content="Go语言文档中文版,Go语言中文网,中国 Golang 社区,Go语言学习园地,致力于构建完善的 Golang 中文社区,Go语言爱好者的学习家园。分享 Go 语言知识,交流使用经验">
</head>
<frameset cols="15,85">
<frame src="/static/pkgdoc/i.html">
<frame name="main" src="/static/pkgdoc/main.html" tppabs="main.html" >
<noframes>
</noframes>
<div>hello1</div>
<div>hello2</div>
<div>hello3</div>
<div>hello4</div>
<div>
haha
hehe
xixi
hoho
</div>
</frameset>
</html>`
//ret := regexp.MustCompile(`<div>(.*)</div>`)
ret := regexp.MustCompile(`<div>(?s:(.*?))</div>`)
subStr := ret.FindAllStringSubmatch(str, -1)
for _, data := range subStr {
fmt.Println(data[0])
fmt.Println(data[1])
}
}
输出结果:
<div>hello1</div>
hello1
<div>hello2</div>
hello2
<div>hello3</div>
hello3
<div>hello4</div>
hello4
<div>
haha
hehe
xixi
hoho
</div>
haha
hehe
xixi
hoho
默认情况下.
能匹配任意字符,不能匹配\n
(?s:(.*?))
- ?s:单行模式。使
.
可以匹配\n
- .*?: 匹配
.
越少越好的匹配方法
<div>xxx</div><div>yyy</div><div>zzz</div>
1 2 3 4 5 6
要求匹配<div></div>之间的内容
越多越好匹配: 1-6
越少越好匹配: 1-2
结论:在字符串中匹配带有匹配参考项的子串时,使用匹配参考项起始(?s:(.*?))匹配参考项结尾