package main 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)) //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)) }
$ go run regular-expressions.go
true true peach [0 5] [peach ea] [0 5 1 3] [peach punch pinch] [[0 5 1 3] [6 11 7 9] [12 17 13 15]] [peach punch] true p([a-z]+)ch a <fruit> a PEACH