golang 中的 regexp 包

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

正則文法 google/re2

Printf 文法 

 

幾個函數方法

名稱 說明 備忘
Match 驗證Regex是否匹配 []byte  -
MatchString 驗證Regex是否匹配 string  -
FindAllString Regexp的方法,匹配字串,返回匹配結果組成一個 []string。限定參數 -1表示不限定,其它表示限定。  -
FindAllStringSubmatch Regexp的方法,返回一個 [][]string  -

 

樣本

MatchString

func MatchString(pattern string, s string) (matched bool, err error)
matched, err := regexp.MatchString("foo.*", "seafood")fmt.Println(matched, err)matched, err = regexp.MatchString("bar.*", "seafood")fmt.Println(matched, err)matched, err = regexp.MatchString("a(b", "seafood")fmt.Println(matched, err)/*output:true <nil>false <nil>false error parsing regexp: missing closing ): `a(b`*/

FindAllString

func (re *Regexp) FindAllString(s string, n int) []string
re := regexp.MustCompile("a.")fmt.Println(re.FindAllString("paranormal", -1))fmt.Println(re.FindAllString("paranormal", 2))fmt.Println(re.FindAllString("graal", -1))fmt.Println(re.FindAllString("none", -1))/*output:[ar an al][ar an][aa][]*/

FindAllStringSubmatch

func (re *Regexp) FindAllStringSubmatch(s string, n int) [][]string
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))/*output:[["ab" ""]][["axxb" "xx"]][["ab" ""] ["axb" "x"]][["axxb" "xx"] ["ab" ""]]*/

FindString

func (re *Regexp) FindString(s string) string
re := regexp.MustCompile("fo.?")fmt.Printf("%q\n", re.FindString("seafood"))fmt.Printf("%q\n", re.FindString("meat"))/*output:"foo"""*/

FindStringSubmatch

func (re *Regexp) FindStringSubmatch(s string) []string
re := regexp.MustCompile("a(x*)b(y|z)c")fmt.Printf("%q\n", re.FindStringSubmatch("-axxxbyc-"))fmt.Printf("%q\n", re.FindStringSubmatch("-abzc-"))/*output:["axxxbyc" "xxx" "y"]["abzc" "" "z"]*/

 

註:

1)這裡的 %q,表示雙引號顯示。

2)FindAllStringSubmatch 與 FindStringSubmatch 的區別

re := regexp.MustCompile("a(x*)b")fmt.Printf("%q\n", re.FindAllStringSubmatch("-ab-axb-", -1))fmt.Printf("%q\n", re.FindStringSubmatch("-ab-axb-"))/*output:[["ab" ""] ["axb" "x"]]["ab" ""]*/

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.