go regexp正則

regexp包是go中內置的專門處理正則的包

package main
import "bytes"
import "fmt"
import "regexp"
func main() {
    // 正則,返回true 或者 false
    match, _ := regexp.MatchString("p([a-z]+)ch", "peach")
    // true
    fmt.Println(match)
    // 返回regexp struct
    r, _ := regexp.Compile("p([a-z]+)ch")
    // 匹配單個字符串,true
    fmt.Println(r.MatchString("peach"))
    // 返回匹配的字符串 peach
    fmt.Println(r.FindString("peach punch"))
    // 返回匹配的字符串的下標數組 [0 5]
    fmt.Println(r.FindStringIndex("peach punch"))
    // 返回 p([a-z]+)ch 和 ([a-z]+)匹配的字符串,即匹配的字符串和匹配的內容,返回字符串數組 [peach ea]
    fmt.Println(r.FindStringSubmatch("peach punch"))
    // 匹配的字符串和匹配的內容的下標 [0 5 1 3]
    fmt.Println(r.FindStringSubmatchIndex("peach punch"))
    // 字符串裏匹配的字符,返回字符串數組,無限制 [peach punch pinch]
    fmt.Println(r.FindAllString("peach punch pinch", -1))
    // [[0 5 1 3] [6 11 7 9] [12 17 13 15]]
    fmt.Println(r.FindAllStringSubmatchIndex(
        "peach punch pinch", -1))
    // 字符串裏匹配的字符,返回字符串數組, 限制2個[peach punch]
    fmt.Println(r.FindAllString("peach punch pinch", 2))
    // 字節匹配 true
    fmt.Println(r.Match([]byte("peach")))
    // 將匹配到的字符串進行處理
    r = regexp.MustCompile("p([a-z]+)ch")
    fmt.Println(r)// p([a-z]+)ch
    // a <fruit>
    fmt.Println(r.ReplaceAllString("a peach", "<fruit>"))
    //  帶函數的匹配處理 a PEACH
    in := []byte("a peach")
    out := r.ReplaceAllFunc(in, bytes.ToUpper)
    fmt.Println(string(out))
}
發佈了95 篇原創文章 · 獲贊 6 · 訪問量 23萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章