go语言正则表达(小记录)

go语言的正则表达

go语言提供标准库 regexp 包

使用
. 	匹配除换行符以外的任意字符
\w 	匹配字母或数字或下划线或汉字
\s 	匹配任意的空白符
\d 	匹配数字
\b 	匹配单词的开始或结束
^ 	匹配字符串的开始
$ 	匹配字符串的结束

* 	重复零次或更多次
+ 	重复一次或更多次
? 	重复零次或一次
{n} 	重复n次
{n,} 	重复n次或更多次
{n,m} 	重复n到m次

example

	reg := regexp.MustCompile(`^z.*l$`)
	result := reg.FindAllString("zhangsanl", -1)
	fmt.Printf("%v\n", result)

	reg1 := regexp.MustCompile(`^z(.*)l$`)
	result1 := reg1.FindAllString("zhangsand", -1)
	fmt.Printf("%v\n", result1)

	reg2 := regexp.MustCompile(`^z(.{1})(.{1})(.*)l$`)
	result2 := reg2.FindAllStringSubmatch("zhangsanl", -1)
	fmt.Printf("%v\n", result2)

简单抓取网页中标签中文字

// simple_crawler
package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
	"regexp"
)
func main() {
	url := "https://movie.douban.com/subject/24751763/"
	resp, err := http.Get(url)
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()
	sHtml, _ := ioutil.ReadAll(resp.Body)
	reg := regexp.MustCompile(`<span\s*property="v:itemreviewed">(.*)</span>`)
	result := reg.FindAllStringSubmatch(string(sHtml), -1)
	fmt.Println(result[0][1])
}

猜你喜欢

转载自blog.csdn.net/u010505805/article/details/94114941