go语言之正则表达式

栏目: Go · 发布时间: 7年前

go语言之正则表达式

//regexp
package main

import (
    "fmt"
    "regexp"
)

func main()  {
    //需要匹配的模式
    //reg := regexp.MustCompile("\\w+") 正则表达式中的\需要转义
    reg := regexp.MustCompile(`^z.*1$`)
    //返回匹配到的结果
    result := reg.FindAllString("zhangsan1", -1)
    fmt.Printf("%v\n", result)

    //演示一个匹配不到的例子
    reg1 := regexp.MustCompile(`^z(.*)1$`)
    result1 := reg1.FindAllString("zhangsand", -1)
    fmt.Printf("%v\n", result1)

    reg2 := regexp.MustCompile(`^z(.{1})(.{1})(.*)1$`)
    result2 := reg2.FindAllString("zhangsan1", -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])

    reg1 := regexp.MustCompile(`<strong\s*class="ll\s*rating_num"\s*property="v:average">(.*)</strong>`)
    result1 := reg1.FindAllStringSubmatch(string(sHtml), -1)

    fmt.Println(result1[0][1])
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Numerical Linear Algebra

Numerical Linear Algebra

Lloyd N. Trefethen、David Bau III / SIAM: Society for Industrial and Applied Mathematics / 1997-06-01 / USD 61.00

Numerical Linear Algebra is a concise, insightful, and elegant introduction to the field of numerical linear algebra.一起来看看 《Numerical Linear Algebra》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换