一.获得初始页面内容
gopm get -g -v golang.org/x/text //引入gbk库
报错: bash: gopm: command not found
解决方法: 使用gopm 完成安装
gopm--Go Package Manager 的缩写。是go 上的包管理工具,十分好用。 gopm
1.gopm 安装:
这个十分简单只需一条命令就可以了:
go get -u github.com/gpmgo/gopm //亲测可用
2.使用 gopm安装需要的包
gopm 具有丰富的包管理功能,具体的管理命令可以参考官方文档(官方文档有中文版 各位爽不爽)链接
这里只需要一条命令就可以搞定了:
gopm bin -d $GOPATH/bin PackageName

二.正则表达式获取邮件地址
1package main 2 3import ( 4 "fmt" 5 "regexp" 6) 7 8const text = ` 9my email is lxw@qq.com 10email2 is aa@def.com 11email3 is bb@eft.com.cn 12` 13 14func main() { 15 re := regexp.MustCompile(`([a-zA-Z0-9]+)@([a-zA-Z0-9]+)(\.[a-zA-Z0-9]+)`) 16 match := re.FindAllStringSubmatch(text, -1) 17 for _, m := range match { 18 fmt.Println(m) 19 } 20}
2.提取城市和url
1package main 2 3import ( 4 "fmt" 5 "io/ioutil" 6 "net/http" 7 "regexp" 8) 9 10func main() { 11 resp, err := http.Get("http://www.zhenai.com/zhenghun") 12 if err != nil { 13 panic(err) 14 } 15 defer resp.Body.Close() 16 if resp.StatusCode != http.StatusOK { 17 fmt.Println("Error:status code", resp.StatusCode) 18 return 19 } 20 all, err := ioutil.ReadAll(resp.Body) 21 if err != nil { 22 panic(err) 23 } 24 //fmt.Printf("%s\n", all) 25 printCityList(all) 26} 27 28func printCityList(contents []byte){ 29 re:=regexp.MustCompile(`<a href="(http://www.zhenai.com/zhenghun/[a-z0-9]+)"[^>]*>([^<]+)</a>`) 30 match:=re.FindAllSubmatch(contents,-1) 31 for _,m :=range match { 32 //for _,sub:=range m { 33 // fmt.Printf("%s",sub) 34 //} 35 //fmt.Println() 36 fmt.Printf("city: %s, Url:%s \n",m[2],m[1]) 37 } 38 39 fmt.Printf("matches found:%d\n",len(match)) 40}
本文同步分享在 博客“lxw1844912514”(CSDN)。
如有侵权,请联系 support@oschina.cn 删除。
本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一起分享。