Golang 正則表達式


  go語言的正則表達式匹配,可以使用go語言的regexp包。

  go語言的正則表達式和其他語言的正則表達式規則都是一樣的,只是調用的函數不同而已

  推薦在構造正則表達式時,使用` pattern `格式。

regexp.Match

  func Match(pattern string, b []byte) (matched bool, err error)

package main

import (
	"fmt"
	"regexp"
)

func main() {
	matched, err := regexp.Match("^abc.*z$", []byte("abcdefgz"))
	fmt.Println(matched, err) //true nil

	matched, err = regexp.Match("^abc.*z$", []byte("bcdefgz"))
	fmt.Println(matched, err) //false nil
}

  

regexp.MatchString

  func MatchString(pattern string, s string) (matched bool, err error)

package main

import (
	"fmt"
	"regexp"
)

func main() {
	matched, err := regexp.MatchString("^abc.*z$", "abcdefgz")
	fmt.Println(matched, err) //true <nil>

	matched, err = regexp.MatchString("^abc.*z$", "bcdefgz")
	fmt.Println(matched, err) //false <nil>
}

 

regexp.Compile

  func Compile(expr string) (*Regexp, error)

  返回一個實現了regexp的對象指針,可以使用返回值調用regexp中定義的方法,如Match,MatchString,findXXX等

//func Compile(expr string) (*Regexp, error)
r, _ := regexp.Compile(`f([a-z]+)`)

//func (re *Regexp) Match(b []byte) bool
fmt.Println(r.Match([]byte("foo"))) //true

//func (re *Regexp) MatchString(s string) bool
fmt.Println(r.MatchString("foo")) //true

//func (re *Regexp) FindString(s string) string
//只匹配一次
fmt.Println(r.FindString("foo func")) //foo

//func (re *Regexp) FindStringIndex(s string) (loc []int)
fmt.Println(r.FindStringIndex("demo foo func")) //[5 8]

//func (re *Regexp) FindStringSubmatch(s string) []string
//只匹配一次,返回的結果中,索引為0的值是整個匹配串的值,第二個值是子表達式的值
fmt.Println(r.FindStringSubmatch("this foo func fan")) //[foo oo]

//對於FindStringSubmatch,如果表達式中沒有子表達式,則不檢測子表達式
demo, _ := regexp.Compile(`foo`)
fmt.Println(demo.FindStringSubmatch("foo")) //[foo]

//func (re *Regexp) FindStringSubmatchIndex(s string) []int
fmt.Println(r.FindStringSubmatchIndex("foo func")) //[0 3 1 3]

//func (re *Regexp) FindAllString(s string, n int) []string
//n為-1時,匹配所有符合條件的字符串,n不為-1時,表示只匹配n次
fmt.Println(r.FindAllString("foo func fan", -1)) //[foo func fan]
fmt.Println(r.FindAllString("foo func fan", 2))  //[foo func]

//func (re *Regexp) FindAllStringSubmatchIndex(s string, n int) [][]int
//n同樣是表示匹配的次數,-1表示匹配所有
fmt.Println(r.FindAllStringSubmatchIndex("foo func demo fan", -1))
//[[0 3 1 3] [4 8 5 8] [14 17 15 17]]

//替換

//func (re *Regexp) ReplaceAll(src []byte, repl []byte) []byte
fmt.Println(string(r.ReplaceAll([]byte("this is foo, that is func, they are fan"), []byte("x"))))
//this is x, that is x, they are x

//func (re *Regexp) ReplaceAllString(src string, repl string) string
fmt.Println(r.ReplaceAllString("this is foo, that is func, they are fan", "xx"))
//this is xx, that is xx, they are xx

  

regexp.MustCompile

  和上面的regexp.Compile用法相似。

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM