登录  /  注册
首页 > 后端开发 > Golang > 正文

Go语言使用正则表达式提取网页文本

发布: 2020-01-08 17:47:49
转载
5005人浏览过

Go语言使用正则表达式提取网页文本

示例:在字符串  1000abcd123  中找出前后两个数字。

例子1:匹配到这个字符串的例子 

package main
 
import(
    "fmt"
    "regexp"
)
 
var digitsRegexp = regexp.MustCompile(`(\d+)\D+(\d+)`)
 
func main(){
    someString:="1000abcd123"
    fmt.Println(digitsRegexp.FindStringSubmatch(someString))
}
登录后复制

上面代码输出:

[1000abcd123 1000 123]
登录后复制

例子2:使用带命名的正则表达式

package main
 
import(
    "fmt"
    "regexp"
)
 
var myExp=regexp.MustCompile(`(?P<first>\d+)\.(\d+).(?P<second>\d+)`)
 
func main(){
    fmt.Printf("%+v",myExp.FindStringSubmatch("1234.5678.9"))
}
登录后复制

上面代码输出,所有匹配到的都输出了:

[1234.5678.9 1234 5678 9]
登录后复制

这里的Named capturing groups (?P) 方式命名正则表达式是 python、Go语言特有的, java、c# 是 (?) 命名方式。

例子3:对正则表达式类扩展一个获得所有命名信息的方法,并使用它。

package main
 
import(
    "fmt"
    "regexp"
)
 
//embed regexp.Regexp in a new type so we can extend it
type myRegexp struct{ 
    *regexp.Regexp
}
 
//add a new method to our new regular expression type
func(r *myRegexp)FindStringSubmatchMap(s string) map[string]string{
    captures:=make(map[string]string)
 
    match:=r.FindStringSubmatch(s)
    if match==nil{
        return captures
    }
 
    for i,name:=range r.SubexpNames(){
        //Ignore the whole regexp match and unnamed groups
        if i==0||name==""{
            continue
        }
 
        captures[name]=match[i]
 
    }
    return captures
}
 
//an example regular expression
var myExp=myRegexp{regexp.MustCompile(`(?P<first>\d+)\.(\d+).(?P<second>\d+)`)}
 
func main(){
    mmap:=myExp.FindStringSubmatchMap("1234.5678.9")
    ww:=mmap["first"]
    fmt.Println(mmap)
    fmt.Println(ww)
}
登录后复制


上面代码的输出结果:

map[first:1234 second:9]

1234
登录后复制

例子4,抓取限号信息,并记录到一个Map中。

package main
 
import(
    "fmt"
    iconv "github.com/djimenez/iconv-go"
    "io/ioutil"
    "net/http"
    "os"
    "regexp"
)
 
// embed regexp.Regexp in a new type so we can extend it
type myRegexp struct{
    *regexp.Regexp
}
 
// add a new method to our new regular expression type
func(r *myRegexp)FindStringSubmatchMap(s string)[](map[string]string){
    captures:=make([](map[string]string),0)
 
    matches:=r.FindAllStringSubmatch(s,-1)
 
    if matches==nil{
        return captures
    }
 
    names:=r.SubexpNames()
 
    for _,match:=range matches{
 
        cmap:=make(map[string]string)
 
        for pos,val:=range match{
            name:=names[pos]
            if name==""{
                continue
            }
 
            /*
                fmt.Println("+++++++++")
                fmt.Println(name)
                fmt.Println(val)
            */
            cmap[name]=val
        }
 
        captures=append(captures,cmap)
 
    }
 
    return captures
}
 
// 抓取限号信息的正则表达式
var myExp=myRegexp{regexp.MustCompile(`自(?P<byear>[\d]{4})年(?P<bmonth>[\d]{1,2})月(?P<bday>[\d]{1,2})日至(?P<eyear>[\d]{4})年(?P<emonth>[\d]{1,2})月(?P<eday>[\d]{1,2})日,星期一至星期五限行机动车车牌尾号分别为:(?P<n11>[\d])和(?P<n12>[\d])、(?P<n21>[\d])和(?P<n22>[\d])、(?P<n31>[\d])和(?P<n32>[\d])、(?P<n41>[\d])和(?P<n42>[\d])、(?P<n51>[\d])和(?P<n52>[\d])`)}
 
func ErrorAndExit(err error){
    fmt.Fprintln(os.Stderr,err)
    os.Exit(1)
}
 
func main(){
    response,err:=http.Get("http://www.bjjtgl.gov.cn/zhuanti/10weihao/index.html")
    defer response.Body.Close()
 
    if err!=nil{
        ErrorAndExit(err)
    }
 
    input,err:=ioutil.ReadAll(response.Body)
    if err!=nil{
        ErrorAndExit(err)
    }
    body :=make([]byte,len(input))
    iconv.Convert(input,body,"gb2312","utf-8")
 
    mmap:=myExp.FindStringSubmatchMap(string(body))
 
    fmt.Println(mmap)
}
登录后复制

上述代码输出:

[map[n32:0 n22:9 emonth:7 n11:3 n41:1 n21:4 n52:7 bmonth:4 n51:2 bday:9 n42:6 byear:2012 eday:7 eyear:2012 n12:8 n31:5]
map[emonth:10 n41:5 n52:6 n31:4 byear:2012 n51:1 eyear:2012 n32:9 bmonth:7 n22:8 bday:8 n11:2 eday:6 n42:0 n21:3 n12:7]
map[bday:7 n51:5 n22:7 n31:3 eday:5 n32:8 byear:2012 bmonth:10 emonth:1 eyear:2013 n11:1 n12:6 n52:0 n21:2 n42:9 n41:4]
map[eyear:2013 byear:2013 n22:6 eday:10 bmonth:1 n41:3 n32:7 n31:2 n21:1 n11:5 bday:6 n12:0 n51:4 n42:8 emonth:4 n52:9]]
登录后复制

更多go语言知识请关注PHP中文网go语言教程栏目。

以上就是Go语言使用正则表达式提取网页文本的详细内容,更多请关注php中文网其它相关文章!

智能AI问答
PHP中文网智能助手能迅速回答你的编程问题,提供实时的代码和解决方案,帮助你解决各种难题。不仅如此,它还能提供编程资源和学习指导,帮助你快速提升编程技能。无论你是初学者还是专业人士,AI智能助手都能成为你的可靠助手,助力你在编程领域取得更大的成就。
相关标签:
来源:博客园网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
关于CSS思维导图的课件在哪? 课件
凡人来自于2024-04-16 10:10:18
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2024 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号