Go语言正则模块

基本使用

import "bytes" import "fmt" import "regexp" func main() { //这个测试一个字符串是否符合一个表达式。
    match, _ := regexp.MatchString("p([a-z]+)ch", "peach") fmt.Println(match) //上面咱们是直接使用字符串,可是对于一些其余的正则任务,你须要使用 Compile 一个优化的 Regexp 结构体。
    r, _ := regexp.Compile("p([a-z]+)ch") //这个结构体有不少方法。这里是相似咱们前面看到的一个匹配测试。
    fmt.Println(r.MatchString("peach")) //这是查找匹配字符串的。
    fmt.Println(r.FindString("peach punch")) //这个也是查找第一次匹配的字符串的,可是返回的匹配开始和结束位置索引,而不是匹配的内容。
    fmt.Println(r.FindStringIndex("peach punch")) //Submatch 返回彻底匹配和局部匹配的字符串。例如,这里会返回 p([a-z]+)ch 和 `([a-z]+) 的信息。
    fmt.Println(r.FindStringSubmatch("peach punch")) //相似的,这个会返回彻底匹配和局部匹配的索引位置。
    fmt.Println(r.FindStringSubmatchIndex("peach punch")) //带 All 的这个函数返回全部的匹配项,而不单单是首次匹配项。例如查找匹配表达式的全部项。
    fmt.Println(r.FindAllString("peach punch pinch", -1)) // 后面的int都表明限制的匹配次数 //All 一样能够对应到上面的全部函数。
 fmt.Println(r.FindAllStringSubmatchIndex( "peach punch pinch", -1)) //这个函数提供一个正整数来限制匹配次数。
    fmt.Println(r.FindAllString("peach punch pinch", 2)) //上面的例子中,咱们使用了字符串做为参数,并使用了如 MatchString 这样的方法。咱们也能够提供 []byte参数并将 String 从函数命中去掉。
    fmt.Println(r.Match([]byte("peach"))) //建立正则表示式常量时,可使用 Compile 的变体MustCompile 。由于 Compile 返回两个值,不能用语常量。
    r = regexp.MustCompile("p([a-z]+)ch") fmt.Println(r) //regexp 包也能够用来替换部分字符串为其余值。
    fmt.Println(r.ReplaceAllString("a peach", "<fruit>")) //Func 变量容许传递匹配内容到一个给定的函数中,
    in := []byte("a peach") out := r.ReplaceAllFunc(in, bytes.ToUpper) fmt.Println(string(out)) }

 

配合http模块基本爬虫应用

import ( "fmt"
    "net/http"
    "io/ioutil"
    "regexp" ) func main(){ url := "http://www.cnblogs.com/yxi-liu/p/8542863.html" resp, err := http.Get(url)  // 发送get请求
    if err != nil{    // 处理错误
 panic(err) } defer resp.Body.Close() // 关闭接口
 shtml,_ := ioutil.ReadAll(resp.Body)   //拿到body
 reg := regexp.MustCompile(`<h1 id="title2">(.*)</h1>`)   // 进行正则编译 // 反引号用来建立原生的字符串字面量,这些字符串可能由多行组成(不支持任何转义序列),因此一般用来写正则字符串
 result := reg.FindAllStringSubmatch(string(shtml),-1) //匹配
    fmt.Println(result[0][1]) // 这里返回一个二维数组,[0][0]为匹配到的整个字符串 [0][1]为捕获匹配结果()内的内容
}
相关文章
相关标签/搜索