Go by Example 中文:正則表達式
Go 提供內置的正則表達式。這裏是 Go 中基本的正則相關功能的例子。
go語言的正在表達式示例代碼如下:
// Go by Example 中文:正則表達式
// https://books.studygolang.com/gobyexample/regular-expressions/
// 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("paech punch"))
// 這個也是查找第一次匹配的字符串的,但是返回的匹配開始和結束位置索引,而不是匹配的內容。
fmt.Println(r.FindStringIndex("paech 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
完整的 Go 正則表達式參考,請查閱 regexp 包文檔。
下一個例子: JSON.