Go語言中正則表示式的處理
1 概述
正則表示式,又稱規則表示式,Regular Expression,在程式碼中常簡寫為 regex、regexp 或 RE。正則表示式是對字串操作的一種邏輯公式,就是用事先定義好的一些特定字元、及這些特定字元的組合,組成一個“規則字串”,這個“規則字串”用來表達對字串的一種過濾邏輯。 Perl 語言的正則表示式功能非常強大,很多語言設計正則式支援的時候都參考Perl的正則表示式。因此常用的表示式語法也是 Perl 相容正則表示式。
Go 語言中使用包 regexp
提供對正則表示式的支援。本文說明 regexp
中常用的正則處理方法。
2 獲取正則物件
通過編譯正則表示式,可以得到正則操作物件,用於完成正則的相關處理: 函式:
regexp.Compile(expr string) (*Regexp, error) regexp.MustCompile(str string) *Regexp
reg,err := regexp.Compile(`\d+`) 或 reg := regexp.MustCompile(`\d+`)
3 匹配檢測
函式:
func (re *Regexp) MatchString(s string) bool func (re *Regexp) Match(b []byte) bool
演示字串的匹配:
text := "Hello Gopher,Hello 韓忠康" reg := regexp.MustCompile(`\w+`) fmt.Println(reg.MatchString(text)) // true
4 查詢
函式:
-
func (re *Regexp) FindString(s string) string
,查詢匹配模式的字串,返回左側第一個匹配的結果。 -
func (re *Regexp) FindAllString(s string, n int) []string
,用來查詢匹配模式的字串,返回多個匹配的結果,n 用於限定查詢數量,-1不限制。 -
func (re *Regexp) FindAll(b []byte, n int) [][]byte
,用於在[]byte
中查詢,返回[][]byte
。
匹配全部結果演示為:
text := "Hello Gopher,Hello 韓忠康" reg := regexp.MustCompile(`\w+`) fmt.Println(reg.FindAllString(text)) // [Hello Gopher Hello]
5 查詢匹配位置
以下函式用於獲取匹配正則子字串的位置:
func (re *Regexp) FindStringIndex(s string) (loc []int) func (re *Regexp) FindIndex(b []byte) (loc []int) func (re *Regexp) FindAllStringIndex(s string, n int) [][]int
演示查詢字串最左側匹配位置:
text := "Hello Gopher,Hello 韓忠康" reg := regexp.MustCompile("llo") fmt.Println(reg.FindStringIndex(text)) // [2 5]
6 查詢匹配子模式
以下函式可以查詢子模式,或查詢子模式的位置:
func (re *Regexp) FindStringSubmatch(s string) []string func (re *Regexp) FindAllStringSubmatch(s string, n int) [][]string func (re *Regexp) FindStringSubmatchIndex(s string) []int
演示匹配全部子字串如下:
re := regexp.MustCompile("Go(\w+)") fmt.Println(re.FindAllStringSubmatch("Hello Gopher,Hello GoLang", -1)) // [["Gophoer" "phoer"], ["GoLang", "Lang"]]
7 替換
函式:
func (re *Regexp) ReplaceAllString(src, repl string) string func (re *Regexp) ReplaceAll(src, repl []byte) []byte
re := regexp.MustCompile("Go(\w+)") fmt.Println(re.ReplaceAllString("Hello Gopher,Hello GoLang", "Hank$1")) // Hello Hankpher,Hello HankLang
8 分割
函式:
-
func (re *Regexp) Split(s string, n int) []string
,使用正則分割字串 s ,返回字串切片。n 控制分割的片數,-1為不限制。
reg := regexp.MustCompile("[\s,]") fmt.Println(reg.Split("Hello Gopher,Hello GoLang", -1)) // [Hello Gopher Hello GoLang]
除了以上列舉的較為常用的方法外,請參考 godoc -http=:8088
獲取更全的資訊。