1. 程式人生 > >Go語言正則表示式

Go語言正則表示式

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)) }

返回結果:

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