regexp包是GO语言官方标准库,用来实现正则表达式操作,其采用RE2语法,除了\c
、\C
外,Go语言和 Perl、Python 等语言的正则基本一致。
re.Find
匹配最左侧第一个。
package main
import (
"fmt"
"regexp"
)
func main() {
re := regexp.MustCompile(`foo.?`)
fmt.Printf("%q\n", re.Find([]byte(`seafood fool`)))
}
re.FindAllSubmatch
匹配所有分组
package main
import (
"fmt"
"io"
"net/http"
"regexp"
)
func main() {
client := &http.Client{}
article_url := "https://example.com/a.html"
req, _ := http.NewRequest("GET", article_url, nil)
resp, _ := client.Do(req)
body, _ := io.ReadAll(resp.Body)
re := regexp.MustCompile("guid=\"(.*?)\";")
guid := re.FindAllSubmatch(body, 1)
fmt.Printf("%q\n", guid[0][1])
}