Go正則表達式使用

準則

  • 默認是最短匹配,只要字符串知足條件就返回。
  • 若是沒有匹配到,都是返回爲nil
  • 若是須要作最長匹配,調用Longest()函數。
  • 正則表達式功能:匹配(macth),查找(find)和替換(replace)。
  • 存在長度選擇的函數,傳入<0的數字表示匹配所有。

使用regexp調用

Match,MatchReader和 MatchString

// 判斷b中是夠包含pattern可以組成的任意字符串
func Match(pattern string, b []byte) (matched bool, err error) // 判斷reader r中返回的字符串是否包含pattern可以組成的任意字符串 func MatchReader(pattern string, r io.RuneReader) (matched bool, err error) // 判斷字符串s中是否包含pattern可以組成的任意字符串 func MatchString(pattern string, s string) (matched bool, err error) 複製代碼

Compile 和 MushCompile

  • func Compile(expr string) (*Regexp, error)
  • func MustCompile(str string) *Regexp

Compile:返回Regexp對象,方便調用指針函數。html

MustCompile:同Compile,解析表達式失敗,會panic。golang

在匹配文本時,該正則表達式會盡量早的開始匹配,而且在匹配過程當中選擇回溯搜索到的第一個匹配結果。這種模式被稱爲leftmost-first,另一般狀況下使用MustCompile便可。正則表達式

使用regexp.Regexp對象來調用

Find 和 FindAll

  • func (re *Regexp) Find(b []byte) []byte
  • func (re *Regexp) FindAll(b []byte, n int) [][]byte

Find返回保管正則表達式re在b中的最左側的一個匹配結果的[]byte切片。若是沒有匹配到,會返回nil,最多匹配一個。bash

re := regexp.MustCompile(`foo.?`)
fmt.Printf("%q\n", re.Find([]byte(`seafood fool`)))
複製代碼
re := regexp.MustCompile(`foo.?`)
fmt.Printf("%q\n", re.FindAll([]byte(`seafood fool`), -1))
複製代碼

FindAll功能與Find同樣,只是返回所有知足條件的數據。函數

FindString 和 FindAllString

  • func (re *Regexp) FindString(s string) string
  • func (re *Regexp) FindAllString(s string, n int) []string

FindFindAll同樣,只是針對字符串string操做。spa

FindIndex 和 FindAllIndex

  • func (re *Regexp) FindIndex(b []byte) (loc []int)3d

  • func (re *Regexp) FindAllIndex(b []byte, n int) [][]int指針

FindIndex, 返回b中知足匹配字符串部分的起始位置,一樣是**「leftmost-first」**原則,loc包含起止位置。若是沒有找到,直接返回nilcode

FindAllIndex,功能和FindIndex保持一致,只是匹配多個,n決定了匹配的位置。regexp

FindStringIndex 和 FindAllStringIndex

  • func (re *Regexp) FindStringIndex(s string) (loc []int)
  • func (re *Regexp) FindAllStringIndex(s string, n int) [][]int

FindIndexFindAllIndex使用方式相似,只是針對的是字符串string。

FindStringSubmatch 和 FindAllStringSubmatch

  • func (re *Regexp) FindStringSubmatch(s string) []string

FindStringSubmatch:採用左匹配原則,最多匹配一個,若是沒有的話,返回nil。對於返回的[]string,分別標示匹配的字符串,子串。

re := regexp.MustCompile(`a(x*)b(y|z)c`)
fmt.Printf("%q\n", re.FindStringSubmatch("-axxxbyc-"))
fmt.Printf("%q\n", re.FindStringSubmatch("-abzc-"))
複製代碼

輸出結果:

["axxxbyc" "xxx" "y"]
["abzc" "" "z"]
複製代碼
  • func (re *Regexp) FindAllStringSubmatch(s string, n int) [][]string

FindStringSubmatch使用相似,只是能顧選擇匹配的長度,-1表示匹配到末尾。

re := regexp.MustCompile(`a(x*)b`)
fmt.Printf("%q\n", re.FindAllStringSubmatch("-ab-", -1))
fmt.Printf("%q\n", re.FindAllStringSubmatch("-axxb-", -1))
fmt.Printf("%q\n", re.FindAllStringSubmatch("-ab-axb-", -1))
fmt.Printf("%q\n", re.FindAllStringSubmatch("-axxb-ab-", -1))
複製代碼

輸出結果:

[["ab" ""]]
[["axxb" "xx"]]
[["ab" ""] ["axb" "x"]]
[["axxb" "xx"] ["ab" ""]]
複製代碼

FindSubmatchIndex 和 FindAllSubmatchIndex

  • func (re *Regexp) FindSubmatchIndex(b []byte) []int
  • func (re *Regexp) FindAllSubmatchIndex(b []byte, n int) [][]int 計算子串在源串中的位置,已經存在(x*)等返回結果處理,若是沒有返回nil

另外,index返回爲左閉右開的模式,示例中的2,2表示空字符串的意思。 而且,不會存在重合匹配的,好比說"-axxb-ab-"去匹配a(x*)b,不會存在第一個a和最後一個b結合的狀況,若是使用Longest就會匹配最長的。

re := regexp.MustCompile(`a(x*)b`)
// Indices:
// 01234567 012345678
// -ab-axb- -axxb-ab-
fmt.Println(re.FindAllStringSubmatchIndex("-ab-", -1))
fmt.Println(re.FindAllStringSubmatchIndex("-axxb-", -1))
fmt.Println(re.FindAllStringSubmatchIndex("-ab-axb-", -1))
fmt.Println(re.FindAllStringSubmatchIndex("-axxb-ab-", -1))
fmt.Println(re.FindAllStringSubmatchIndex("-foo-", -1))
複製代碼

輸出結果:

[[1 3 2 2]] // 2 2 表示爲空
[[1 5 2 4]]
[[1 3 2 2] [4 7 5 6]]
[[1 5 2 4] [6 8 7 7]]
[]
複製代碼

FindStringSubmatchIndex 和 FindAllStringSubmatchIndex

  • func (re *Regexp) FindStringSubmatchIndex(s string) []int
  • func (re *Regexp) FindAllStringSubmatchIndex(s string, n int) [][]int

FindSubmatchIndexFindAllSubmatchIndex保持一致。

Longest

  • func (re *Regexp) Longest() 獲取最長匹配的知足條件的內容。
re := regexp.MustCompile(`a(|b)`)
fmt.Println(re.FindString("ab"))
re.Longest()
fmt.Println(re.FindString("ab"))
複製代碼

輸出結果:

a
ab
複製代碼

下面這種狀況不會最長匹配。

re := regexp.MustCompile(`a(x*)b`)
re.Longest()
fmt.Println(re.FindString("-axxb-ab-")) // axxb,不會存在第一個a和最後一個b組合的過程。
複製代碼

Match,MatchString和MatchReader

  • func (re *Regexp) Match(b []byte) bool
  • func (re *Regexp) MatchString(s string) bool
  • func (re *Regexp) MatchReader(r io.RuneReader) bool

判斷bsr返回的數據是否知足正則表達式,返回true或者false

NumSubexp

  • func (re *Regexp) NumSubexp() int

返回分組的數量。

re0 := regexp.MustCompile(`a.`)
fmt.Printf("%d\n", re0.NumSubexp())

re := regexp.MustCompile(`(.*)((a)b)(.*)a`)
fmt.Println(re.NumSubexp())
複製代碼

輸出結果:

0
4
複製代碼

ReplaceAll 和 ReplaceAllString

  • func (re *Regexp) ReplaceAll(src, repl []byte) []byte
  • func (re *Regexp) ReplaceAllString(src, repl string) string

ReplaceAllStringReplaceAll使用方式相同。

re := regexp.MustCompile(`a(x*)b`)
fmt.Printf("%s\n", re.ReplaceAll([]byte("-ab-axxb-"), []byte("T")))  
fmt.Printf("%s\n", re.ReplaceAll([]byte("-ab-axxb-"), []byte("$1"))) // $1表示匹配的第一個子串,這是ab的中間無字符串,因此$1爲空,而後使用空去替換知足正則表達式的部分。
fmt.Printf("%s\n", re.ReplaceAll([]byte("-ab-axxb-"), []byte("$1W"))) // "$1W"等價與"$(1W)",值爲空,將知足條件的部分徹底替換爲空。
fmt.Printf("%s\n", re.ReplaceAll([]byte("-ab-axxb-"), []byte("${1}W"))) // ${1}匹配(x*),保留。輸出-W-xxW-
複製代碼

輸出結果:

-T-T-
--xx-
---
-W-xxW-
複製代碼
s := "Hello World, 123 Go!"
//定義一個正則表達式reg,匹配Hello或者Go
reg := regexp.MustCompile(`(Hell|G)o`)

s2 := "2019-12-01,test"
//定義一個正則表達式reg2,匹配 YYYY-MM-DD 的日期格式
reg2 := regexp.MustCompile(`(\d{4})-(\d{2})-(\d{2})`)

//最簡單的狀況,用「T替換」"-ab-axxb-"中符合正則"a(x*)b"的部分
reg3 := regexp.MustCompile("a(x*)b")
fmt.Println(re.ReplaceAllString("-ab-axxb-", "T")) // -T-T-

//${1}匹配"Hello World, 123 Go!"中符合正則`(Hell|G)`的部分並保留,去掉"Hello"與"Go"中的'o'並用"ddd"追加
rep1 := "${1}ddd"
fmt.Printf("%q\n", reg.ReplaceAllString(s, rep1)) // Hellddd World, 123 Gddd!

//首先,"2019-12-01,test"中符合正則表達式`(\d{4})-(\d{2})-(\d{2})`的部分是"2019-12-01",將該部分匹配'(\d{4})'的'2019'保留,去掉剩餘部分
rep2 := "${1}"
fmt.Printf("%q\n", reg2.ReplaceAllString(s2,rep2)) // 2019,test

//首先,"2019-12-01,test"中符合正則表達式`(\d{4})-(\d{2})-(\d{2})`的部分是"2019-12-01",將該部分匹配'(\d{2})'的'12'保留,去掉剩餘部分
 rep3 := "${2}"
fmt.Printf("%q\n", reg2.ReplaceAllString(s2,rep3)) // 12,test

//首先,"2019-12-01,test"中符合正則表達式`(\d{4})-(\d{2})-(\d{2})`的部分是"2019-12-01",將該部分匹配'(\d{2})'的'01'保留,去掉剩餘部分,並追加"13:30:12"
rep4 := "${3}:13:30:12"
fmt.Printf("%q\n", reg2.ReplaceAllString(s2,rep4)) // 01:13:30:12,test
}
複製代碼

ReplaceAllFunc 和 ReplaceAllStringFunc

  • func (re *Regexp) ReplaceAllFunc(src []byte, repl func([]byte) []byte) []byte
  • func (re *Regexp) ReplaceAllStringFunc(src string, repl func(string) string) string

將匹配出來知足條件的[]byte做爲參數傳入函數中。

re := regexp.MustCompile(`[^aeiou]`)
fmt.Println(re.ReplaceAllStringFunc("seafood fool", strings.ToUpper))
複製代碼

二者使用方式相似。

ReplaceAllLiteral 和 ReplaceAllLiteralString

  • func (re *Regexp) ReplaceAllLiteral(src, repl []byte) []byte
  • func (re *Regexp) ReplaceAllLiteralString(src, repl string) string

匹配字面常量,不轉換。

re := regexp.MustCompile(`a(x*)b`)
fmt.Println(re.ReplaceAllLiteralString("-ab-axxb-", "T"))
fmt.Println(re.ReplaceAllLiteralString("-ab-axxb-", "$1"))
fmt.Println(re.ReplaceAllLiteralString("-ab-axxb-", "${1}"))
複製代碼

輸出結果:

-T-T-
-$1-$1-
-${1}-${1}-
複製代碼

關於$1說明:

Expand 和 ExpandString

  • func (re *Regexp) Expand(dst []byte, template []byte, src []byte, match []int) []byte
  • func (re *Regexp) ExpandString(dst []byte, template string, src string, match []int) []byte

Expand返回新生成的將template添加到dst後面的切片。在添加時,Expand會將template中的變量替換爲從src匹配的結果。match應該是被FindSubmatchIndex返回的匹配結果起止位置索引。(一般就是匹配src,除非你要將匹配獲得的位置用於另外一個[]byte)

在template參數裏,一個變量表示爲格式如:$name${name}的字符串,其中name是長度>0的字母、數字和下劃線的序列。一個單純的數字字符名如$1會做爲捕獲分組的數字索引;其餘的名字對應(?P...)語法產生的命名捕獲分組的名字。超出範圍的數字索引、索引對應的分組未匹配到文本、正則表達式中未出現的分組名,都會被替換爲空切片。

$name格式的變量名,name會盡量取最長序列:$1x等價於${1x}而非${1}x$10等價於${10}而非${1}0。所以$name適用在後跟空格/換行等字符的狀況,${name}適用全部狀況。

若是要在輸出中插入一個字面值'$',在template裏可使用$$

其餘示例

解析網址

flysnowRegexp := regexp.MustCompile(`^http://www.flysnow.org/([\d]{4})/([\d]{2})/([\d]{2})/([\w-]+).html$`)
params := flysnowRegexp.FindStringSubmatch("http://www.flysnow.org/2018/01/20/golang-goquery-examples-selector.html")
// 返回[]string{}數據類型
for _, param := range params {
	fmt.Println(param)
}
複製代碼

輸出結果:

http://www.flysnow.org/2018/01/20/golang-goquery-examples-selector.html
2018
01
20
golang-goquery-examples-selector
複製代碼
相關文章
相關標籤/搜索